Express central error handling with app.use

1.1k views Asked by At

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?

1

There are 1 answers

2
Jose Mato On BEST ANSWER

Express is based on middlewares, so, if you wanna catch the errors inside the middleware, you should call the error middleware:

app.get('/',(req,res)=>{
    next(new Error('Testing'));
});

/**
 * middleware to catch errors happened before this middleware
 * express knows this middleware is for error handling because it has
 * four parameters (err, req, res, next)
 **/
app.use((err, req, res, next) => {
  res.status(500).send({
    message: err.message,
  });
});

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('/')