Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

exit from express middleware with specific http status

exit from express middleware with specific http status

Problem

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.

Problem courtesy of: Grofit

Solution

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

Solution courtesy of: Pickels

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

exit from express middleware with specific http status

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×