Come specificare il codice di errore HTTP?


161

Ho provato:

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

e:

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

ma viene sempre annunciato un codice di errore di 500.


1
La mia risposta a una domanda relativa potrebbe aiutare: stackoverflow.com/questions/10170857/...
— Pickels

2
Potresti aggiornare la risposta accettata?
— Dan Mandle,

Risposte:


293

Per i documenti Express (versione 4+), è possibile utilizzare:

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');

37
+1 per l'utilizzo dell'ultima versione dell'API. Se vuoi inviarne di più lungo il filo, res.status(400).json({ error: 'message' })
— fai

1
@Mikel se non hai una variabile di risposta, non puoi inviare una risposta.
— Dan Mandle

1
Questo è tutto deprecato ora, dovresti usare res.sendStatus(401);.
— Cipi,

1
Questa risposta sarebbe molto più completa se finisse con res.send('Then you shall die').
— goodvibration

1
@Cipi Hai una fonte per questo? La documentazione non indica che .status()è obsoleta. .sendStatus()è solo una scorciatoia per .status(code).send(codeName)dove codeNameè il testo di risposta HTTP standard per il dato code.
— James Coyle,

78

Una semplice fodera;

res.status(404).send("Oh uh, something went wrong");

20

Vorrei centralizzare la creazione della risposta di errore in questo modo:

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})
});

Quindi ho sempre lo stesso formato di output dell'errore.

PS: ovviamente potresti creare un oggetto per estendere l'errore standard in questo modo:

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);

16

Puoi usare res.send('OMG :(', 404);solores.send(404);


Ma voglio che il codice di errore venga inviato al middleware eventHandler, quindi viene visualizzata la pagina di errore personalizzata di express.
— tech-man,

12
Per chiunque legga questo nel 2016: secondo Express 4.x, res.send(404)è deprecato. È adesso res.sendStatus(404). expressjs.com/en/api.html#res.sendStatus
— 0xRm,

12

In Express 4.0 hanno capito bene :)

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')

11

La versione del middleware errorHandler in bundle con alcune versioni (forse precedenti?) Di Express sembra avere il codice di stato hardcoded. La versione documentata qui: http://www.senchalabs.org/connect/errorHandler.html invece ti consente di fare ciò che stai cercando di fare. Quindi, forse provando ad aggiornare all'ultima versione di express / connect.


9

Da quello che ho visto in Express 4.0 questo funziona per me. Questo è un esempio di middleware richiesto per l'autenticazione.

function apiDemandLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    console.log('isAuth', req.isAuthenticated(), req.user);
    if (req.isAuthenticated())
        return next();

    // If not return 401 response which means unauthroized.
    var err = new Error();
    err.status = 401;
    next(err);
}

8

Vecchia domanda, ma ancora su Google. Nella versione corrente di Express (3.4.0), è possibile modificare res.statusCode prima di chiamare next (err):

res.statusCode = 404;
next(new Error('File not found'));

Cosa fa il prossimo?
— Steve K,

nextsta chiamando il gestore successivo che in express.js di solito sta provando a visualizzare le pagine di errore.
— Kurotsuki,

2

express resecated inv.send (body, status). Utilizzare invece res.status (status) .send (body)


2

Provai

res.status(400);
res.send('message');

..ma mi stava dando errore :

(nodo: 208) UnhandledPromiseRejectionWarning: errore: impossibile impostare le intestazioni dopo l'invio.

Questo lavoro per me

res.status(400).send(yourMessage);

0

Vorrei raccomandare di gestire l'invio di codici di errore http utilizzando il pacchetto Boom .

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.