How to specify HTTP error code?

后端 未结 11 2640
余生分开走
余生分开走 2020-12-02 13:48

I have tried:

app.get(\'/\', function(req, res, next) {
    var e = new Error(\'error message\');
    e.status = 400;
    next(e);
});

and:

11条回答
  •  無奈伤痛
    2020-12-02 14:30

    I'd like to centralize the creation of the error response in this way:

    app.get('/test', function(req, res){
      throw {status: 500, message: 'detailed message'};
    });
    
    app.use(function (err, req, res, next) {
      res.status(err.status || 500).json({status: err.status, message: err.message})
    });
    

    So I have always the same error output format.

    PS: of course you could create an object to extend the standard error like this:

    const AppError = require('./lib/app-error');
    app.get('/test', function(req, res){
      throw new AppError('Detail Message', 500)
    });
    

    'use strict';
    
    module.exports = function AppError(message, httpStatus) {
      Error.captureStackTrace(this, this.constructor);
      this.name = this.constructor.name;
      this.message = message;
      this.status = httpStatus;
    };
    
    require('util').inherits(module.exports, Error);
    

提交回复
热议问题