Skip to content

Instantly share code, notes, and snippets.

@benqus
Last active August 23, 2024 06:26
Show Gist options
  • Save benqus/1c9654362e69365d8933d82289c8e1a9 to your computer and use it in GitHub Desktop.
Save benqus/1c9654362e69365d8933d82289c8e1a9 to your computer and use it in GitHub Desktop.
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
};
}
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;
}
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();
@cbarlow1993
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment