Skip to content

Instantly share code, notes, and snippets.

@prasann
Created May 25, 2020 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prasann/b6ad07b3962b6ea2953fef027df5d10b to your computer and use it in GitHub Desktop.
Save prasann/b6ad07b3962b6ea2953fef027df5d10b to your computer and use it in GitHub Desktop.
Centralized error handler - Express application
import logger from './logger';
export class AppError extends Error {
statusCode: number;
message: string;
constructor(statusCode, message) {
super(message);
this.statusCode = statusCode;
this.message = message;
}
}
const handleKnownExceptions = (err, res) => {
logger.error(err);
const { statusCode, message } = err;
res.status(statusCode).json({error: {message});
};
const handleUnknownExceptions = (err, res) => {
logger.error(err);
res.status(500).json({ error: {message: 'Something went wrong.' }});
};
export const handleError = (err, res) => {
err instanceof AppError ? handleKnownExceptions(err, res) : handleUnknownExceptions(err, res);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment