使用 Node.js + Express (4) + Mongoose(使用 promises 而不是回调),我不知道如何整理我的错误处理。
我得到的(相当简化的)是:
app.get('/xxx/:id', function(request, response) {
Xxx.findById(request.params.id).exec()
.then(function(xxx) {
if (xxx == null) throw Error('Xxx '+request.params.id+' not found');
response.send('Found xxx '+request.params.id);
})
.then(null, function(error) { // promise rejected
switch (error.name) {
case 'Error':
response.status(404).send(error.message); // xxx not found
break;
case 'CastError':
response.status(404).send('Invalid id '+request.params.id);
break;
default:
response.status(500).send(error.message);
break;
}
});
});
在这里,在“promise rejected”部分的开关中,Error
是我为未找到的潜在有效 ID 而抛出的错误,CastError
是 Cast to ObjectId failed 由 Mongoose 因无效 ID 抛出,并且 500 错误可以通过将 throw Error()
错误输入为 throw Err() 来触发
(导致 ReferenceError: Err is not defined)。
但是像这样,我的每条路线都有这个笨拙的大开关来处理不同的错误。
如何集中处理错误?能否以某种方式将开关隐藏到某些中间件中?
(我确实希望我可以在“promise rejected” block 中使用 throw error;
重新抛出,但我没能成功)。
最佳答案
我会创建中间件来处理错误。使用 next()
处理 404。和 next(err)
用于其他错误。
app.get('/xxx/:id', function(req, res, next) {
Xxx.findById(req.params.id).exec()
.then(function(xxx) {
if (xxx == null) return next(); // Not found
return res.send('Found xxx '+request.params.id);
})
.then(null, function(err) {
return next(err);
});
});
404处理程序
app.use(function(req, res) {
return res.send('404');
});
错误处理器
app.use(function(err, req, res) {
switch (err.name) {
case 'CastError':
res.status(400); // Bad Request
return res.send('400');
default:
res.status(500); // Internal server error
return res.send('500');
}
});
您可以通过发送像这样的 json 响应来改进这一点:
return res.json({
status: 'OK',
result: someResult
});
或
return res.json({
status: 'error',
message: err
});
关于node.js - 使用 promises 在 Node.js + Express 中处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26470535/