exit from express middleware with specific http status

express, http-status-codes, javascript, middleware, node.js

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

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.

Original source