Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exit from express middleware with specific http status

Hopefully this is a simple one, but I have some custom middleware which I want to return a 404 or 401 etc to the user and stop the propagation of other handlers etc.

I was expecting I could do something like:

function SomeMiddleware(req, res, next) {
   if(user.notRealOrSomething)
   { throw new HttpException(401, "Tough luck buddy"); }

   return next();
}

However cannot find any specific info about how is best to do this.

like image 411
Grofit Avatar asked Aug 02 '13 12:08

Grofit


2 Answers

You are suppose to pass errors to the next() function.

function SomeMiddleware(req, res, next) {
   if(user.notRealOrSomething) {
    return next(throw new HttpException(401, "Tough luck buddy")); 
   }

   next();
}

Any argument you pass to next will be considered an error except 'route' which will skip to the next route.

When next is called with an error the error middleware will be execute.

function (err, req, res, next) {
  // err === your HttpException
}

Express.js will treat any middleware with 4 arguments as error middleware.

Error-handling middleware are defined just like regular middleware, however must be defined with an arity of 4, that is the signature (err, req, res, next):

All of this is pretty well documented at: http://expressjs.com/guide/error-handling.html

like image 160
Pickels Avatar answered Oct 21 '22 13:10

Pickels


Nothing prevents you from using the response object:

res.send(401, "Tough luck buddy");
next('invalid user');
like image 24
kolypto Avatar answered Oct 21 '22 13:10

kolypto