2012-05-12 31 views
74

denedim:HTTP hata kodu nasıl belirlenir?

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

ve:

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

ama her zaman 500 hata kodu duyurulur.

+1

İlgili bir soruya verdiğim yanıt şu konularda yardımcı olabilir: http://stackoverflow.com/questions/10170857/can-i-reuse-the-express-js- hata-görünüm/10556093 # 10556093 – Pickels

+1

Kabul edilen yanıtı günceller misiniz? –

cevap

141

, şunları kullanabilirsiniz:

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

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

< = I Expre gördüğüm kadarıyla 3,8

res.statusCode = 401; 
res.send('None shall pass'); 
+14

+1. Telden daha aşağı göndermek isterseniz, sadece zincir: 'res.status (400) .json ({error: 'message'})' – TyMayn

+0

Bir yanıt değişkeni yoksa ne olur? Bir mongoose doğrulamada, bir yanıt değişkeni yoksa "bir hata" (yeni Hata ('Hata metinim')) ' – Mikel

+0

@Mikel 'i yükseltmem gerekiyor, o zaman bir yanıt gönderemezsiniz. –

13

bazı ile birlikte errorHandler middlewarein res.send('OMG :(', 404); sadece res.send(404);

+0

Ancak hata kodunun eventHandler ara katmanına gönderilmesini istiyorum, bu nedenle ifadenin özel hata sayfası görüntülensin. –

+6

2016'da bunu okuyan herkes için: Express 4.x’e göre, “res.send (404)', kullanımdan kaldırılmıştır. Şimdi res.sendStatus (404) 'dir. http://expressjs.com/en/api.html#res.sendStatus – 0xRm

11

sürümünü kullanabilirsiniz (belki daha eski?) Express sürümleri durum kodu kodlanmış var gibi gözüküyor. Burada belgelenen sürüm: http://www.senchalabs.org/connect/errorHandler.html, yapmaya çalıştığınız şeyi yapmanıza izin verir. Bu yüzden belki de express/connect'in en son sürümüne geçmeyi denemelisiniz.

8

Eski soru, ancak yine de Google’da geliyor. Express (3.4.0) geçerli sürümünde, (err) sonraki çağırmadan önce res.statusCode değiştirebilir: Ekspres (Sürüm 4+) docs Başına

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

Bundan sonra ne yapar? – nottinhill

+0

'next', express.js'de genellikle hata sayfaları oluşturmaya çalışan bir sonraki işleyiciyi çağırıyor. API'nın en son sürümünü kullanmak için – Kurotsuki

5

ss 4.0 bu benim için çalışıyor. Bu, gerekli middleware kimlik doğrulaması örneğidir.

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

Basit bir astar; ekspres 4.0 içinde

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

doğru :) got

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

ben bu şekilde hata yanıtı oluşturulmasını merkezileştirme istiyorum:

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

Yani her zaman var aynı hata çıkış formatı.

Not: Eğer böyle extend the standard error bir nesneyi oluşturabilir tabii:

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

kaldırılmış ekspres res.send (beden, durum). Res.status (status) .send (body) yerine kullanın