How to specify HTTP error code?

后端 未结 11 2602
余生分开走
余生分开走 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:19

    Per the Express (Version 4+) docs, you can use:

    res.status(400);
    res.send('None shall pass');
    

    http://expressjs.com/4x/api.html#res.status

    <=3.8

    res.statusCode = 401;
    res.send('None shall pass');
    
    0 讨论(0)
  • 2020-12-02 14:22

    Old question, but still coming up on Google. In the current version of Express (3.4.0), you can alter res.statusCode before calling next(err):

    res.statusCode = 404;
    next(new Error('File not found'));
    
    0 讨论(0)
  • 2020-12-02 14:24

    I would recommend handling the sending of http error codes by using the Boom package.

    0 讨论(0)
  • 2020-12-02 14:25

    In express 4.0 they got it right :)

    res.sendStatus(statusCode)
    // Sets the response HTTP status code to statusCode and send its string representation as the response body.
    
    res.sendStatus(200); // equivalent to res.status(200).send('OK')
    res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
    res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
    res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
    
    //If an unsupported status code is specified, the HTTP status is still set to statusCode and the string version of the code is sent as the response body.
    
    res.sendStatus(2000); // equivalent to res.status(2000).send('2000')
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-02 14:32

    A simple one liner;

    res.status(404).send("Oh uh, something went wrong");
    
    0 讨论(0)
提交回复
热议问题