Created
May 25, 2020 19:44
-
-
Save prasann/b6ad07b3962b6ea2953fef027df5d10b to your computer and use it in GitHub Desktop.
Centralized error handler - Express application
This file contains hidden or 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
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