Hey guys I want to achieve central error handling in express, I've done this.
app.use(function(err,req,res,next){
logger.error(err);
utils.jsonOutHandler(err,null,res);
next(err);
});
app.get('/',(req,res)=>{
throw new Error('Testing');
});
Also I made a special jsonOutHandler method which sends proper response to the user.
function jsonOutHandler(err, result, out) {
if (err) {
let status = 500;
const message = 'Something broke';
if (err instanceof DbError) {
status = 500;
}
if (err instanceof ValidationError) {
status = 400;
}
if (err instanceof SystemError) {
status = 500;
}
out.status(status).send({message});
return;
}
out.status(result.status).send({data: result.data});
}
But whenever I throw error on '/' route my error handler is never triggered. Why?
Express is based on middlewares, so, if you wanna catch the errors inside the middleware, you should call the error middleware:
I hope you can adapt this example to your requirements. The thing to keep in mind is an error middleware can be used from previous middlewares. In your example you couldn't catch the error because your middleware was defined before your main router app.get('/')