【发布时间】:2014-12-15 17:22:16
【问题描述】:
使用 Node.js + Express (4) + Mongoose(使用 Promise 而不是回调),我无法理清如何整理我的错误处理。
我得到的(相当简化的)是:
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;
}
});
});
在这里,在“承诺被拒绝”部分的开关中,Error 是我为未找到的潜在有效 id 抛出的错误,CastError 是 Cast to ObjectId failed em> 由 Mongoose 抛出一个无效的 id,并且 500 错误可以通过将 throw Error() 错误输入为 throw Err() 来触发(导致 ReferenceError: Err is not defined)。
但是像这样,我的每条路线都有这个笨拙的大开关来处理不同的错误。
如何集中处理错误?开关能否以某种方式隐藏在某些中间件中?
(我确实希望我可以在 'promise denied' 块中使用 throw error; 重新抛出,但我无法让它工作)。
【问题讨论】:
-
你不能让那个错误处理函数全局化(到处都一样吗?),然后在每条路由中将它传递给
.then(null, …)? -
@Bergi:谢谢——我想知道一个全局错误处理函数,我只是觉得应该有一种更“原生”的做事方式。全局错误处理函数工作正常——如果你把它作为答案,我会接受的!
-
@ChrisV 你所说的更“原生”的方式是使用基于承诺的路由器,而不是默认的路由器,它会让你
return Xxx.findById(...然后检查拒绝。我认为 spion 在某个时候写过一篇。
标签: node.js express error-handling mongoose promise