praveen
praveen

Reputation: 11

Middleware in Express

How to catch the error which is throwing in middleware function in router(/test) method

    app.use(function(err, req, res, next) {    
        throw new Error('test');
      next("its failing")    
    })

    app.get('/test',function(req,res,error){

      res.send({ message: error.message });
    })

Upvotes: 1

Views: 72

Answers (2)

praveen
praveen

Reputation: 11

Below snippet is working as expected

var a=function test(req,res,next){
    try {
        throw new Error('test error');
    } catch (err) {
        next(err);
    } 
}

app.get('/test',a, function(req,res){
   res.send(200)
}, (err, req, res, next) => {
    res.status(400).send({ error: err.message });
})

Upvotes: 0

Terry Lennox
Terry Lennox

Reputation: 30675

You can pass variables from your middleware to route handlers using the res.locals object. If you pass the error object you can check for this in your route handler.

app.use(function(req, res, next) {
    try {
        throw new Error('test error');
    } catch (err) {
        res.locals.Error = err;
    }   
    next(); 
})

app.get('/test', function(req,res,error){
    if (res.locals.Error) {
        res.status(500).json({ message: res.locals.Error.message})
    } else {
        res.send("OK");
    }
})

Note: You can also pass an error directly to the next() function. Express will skip any remaining handlers if you do this however. See Express error handling

For example:

app.use(function(req, res, next) {
    try {
        throw new Error('test error');
    } catch (err) {
        next(err);
    }   
})

Upvotes: 1

Related Questions