在Node.js + Express中使用承诺处理错误

使用Node.js + Express(4)+ Mongoose(使用promises而不是callback),我不能理清如何清理error handling。

我所得到的(而非简化的)是:

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没有find的错误, CastError铸造到ObjectId由Mongoose抛出无效ID 失败 ,500错误例如可以通过throw Error()作为throw Err() (导致ReferenceError:Err未定义 )来触发。

但是像这样,我的每条路线都有这个巨大笨拙的开关来处理不同的错误。

我怎样才能集中处理错误? 不知何故,交换机可以塞进一些中间件吗?

(我希望我可以使用throw error;重新抛出throw error;在'promise rejected'块内,但是我一直无法工作)。

我会创build中间件来处理错误。 使用next()作为404s。 和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'); }); 

error handling程序

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