Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.