1

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?

Hrant Nurijanyan
  • 789
  • 2
  • 9
  • 26

1 Answers1

2

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

Jose Mato
  • 2,709
  • 1
  • 17
  • 18
  • Yeah, that works, thanks. So the error middleware must be the LAST middleware i am going to add, and also passing next from all the routes to enter middleware. Am I right? – Hrant Nurijanyan Apr 06 '20 at 21:27
  • depending on the case but lets say, usually yes. A complex example could be custom middlewares errors, for example, you have 4 middlewares declared and after that a middleware to catch the error. Then, another 3 different middlewares with another middleware to catch the errors. Technically it's possible (I am not saying this is a good architecture just is technically a possibility) – Jose Mato Apr 06 '20 at 21:35