Last active
August 23, 2024 06:26
-
-
Save benqus/1c9654362e69365d8933d82289c8e1a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ErrorController } from './types'; | |
function throwIfConditionIsTrue(error: Error | string, condition: boolean): void { | |
if (condition) throw error instanceof Error ? error : new Error(error); | |
} | |
export function throwError(error: Error | string): ErrorController { | |
const when = { | |
isNull: (arg: unknown): void => throwIfConditionIsTrue(error, arg === null), | |
isUndefined: (arg: unknown): void => throwIfConditionIsTrue(error, typeof arg === 'undefined'), | |
isEmpty: (arg: unknown): void => throwIfConditionIsTrue(error, arg == null), | |
isIn: (arg: unknown, matches: Array<any>): void => throwIfConditionIsTrue(error, matches.includes(arg)), | |
// TODO extend here as needed | |
}; | |
return { | |
when, | |
throw: (): void => throwIfConditionIsTrue(error, true), | |
// TODO extend here as needed | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface WhenMatcher { | |
isNull(arg: unknown): void; | |
isUndefined(arg: unknown): void; | |
isEmpty(arg: unknown): void; | |
isIn(arg: unknown, matches: Array<any>): void; | |
// TODO extend here as needed | |
} | |
export interface ErrorController { | |
when: WhenMatcher; | |
throw(): void; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { error } from './throwError'; | |
// Example 1 | |
let resource; | |
const throwGenericError = throwError('Oopsie poopsie'); | |
throwGenericError.when.isUndefined(resource); | |
// Example 2 | |
class ForbiddenError extends Error {} | |
const access = null; | |
const { when: throwForbiddenErrorWhen } = throwError(new ForbiddenError('Forbidden')); | |
throwForbiddenErrorWhen.isNull(access); | |
// Example 3 | |
class NotFoundError extends Error {} | |
const notFoundError = throwError(new NotFoundError('Not Found')); | |
notFoundError.throw(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I thought/think somewhere in the code for some of these uses cases, like resource not found, forbidden, we would throw a ZodError and let that boil up to an error handling middleware tied into Middy which would then format the error appropriately.