How to send a custom http status message in node / express?

前端 未结 9 733
我寻月下人不归
我寻月下人不归 2020-12-12 16:24

My node.js app is modeled like the express/examples/mvc app.

In a controller action I want to spit out a HTTP 400 status with a custom http message. By default the

9条回答
  •  一生所求
    2020-12-12 16:49

    One elegant way to handle custom errors like this in express is:

    function errorHandler(err, req, res, next) {
      var code = err.code;
      var message = err.message;
      res.writeHead(code, message, {'content-type' : 'text/plain'});
      res.end(message);
    }
    

    (you can also use express' built-in express.errorHandler for this)

    Then in your middleware, before your routes:

    app.use(errorHandler);
    

    Then where you want to create the error 'Current password does not match':

    function checkPassword(req, res, next) {
      // check password, fails:
      var err = new Error('Current password does not match');
      err.code = 400;
      // forward control on to the next registered error handler:
      return next(err);
    }
    

提交回复
热议问题