Skip to content

Instantly share code, notes, and snippets.

@SagnikPradhan
Last active January 28, 2021 04:32
Show Gist options
  • Save SagnikPradhan/efcc4bfd3eaddd59d60597c44d651dbd to your computer and use it in GitHub Desktop.
Save SagnikPradhan/efcc4bfd3eaddd59d60597c44d651dbd to your computer and use it in GitHub Desktop.
πŸ’€ Custom error and error handler
export class AppError extends Error {
public readonly name: string;
public readonly isOperational: boolean;
public readonly cause?: Error;
public readonly additionalProps: { [additionalProps: string]: unknown };
constructor({
name,
message,
isOperational,
cause,
...additionalProps
}: {
name: string;
message: string;
isOperational: boolean;
cause?: Error;
[additionalProps: string]: unknown;
}) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
this.name = name;
this.isOperational = isOperational;
this.cause = cause;
this.additionalProps = additionalProps;
if (Error.captureStackTrace) Error.captureStackTrace(this);
}
}
export function handleError(error: Error) {
console.error(error);
if (error instanceof AppError && error.isOperational) return;
else process.exit(1);
}
export function handleAsync<T extends unknown[]>(
asyncFunction: (...args: T) => Promise<void>
) {
return (...args: T) => {
asyncFunction(...(args || [])).catch(handleError);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment