Last active
January 28, 2021 04:32
-
-
Save SagnikPradhan/efcc4bfd3eaddd59d60597c44d651dbd to your computer and use it in GitHub Desktop.
π Custom error and error handler
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 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