您通常根本不想在 Express 中抛出错误,因为除非它被捕获,否则它会在不给用户警告的情况下使进程崩溃,并且很难捕获错误并维护请求上下文以否则这样做.
相反,Express 处理程序中的选择应该是在直接返回错误响应(如您的示例中)和调用 next(err) 之间。在我的应用程序中,我总是使用后者,因为它可以让我设置错误处理中间件,以始终始终如一地处理各种问题案例。
示例如下:
app.get('/something', (req, res, next) => {
// whatever database call or the like
Something.find({ name: 'something'}, (err, thing) => {
// some DB error, we don't know what.
if (err) return next(err);
// No error, but thing wasn't found
// In this case, I've defined a NotFoundError that extends Error and has a property called statusCode set to 404.
if (!thing) return next(new NotFoundError('Thing was not found'));
return res.json(thing);
});
});
然后是一些用于处理错误的中间件,如下所示:
app.use((err, req, res, next) => {
// log the error; normally I'd use debug.js or similar, but for simplicity just console in this example
console.error(err);
// Check to see if we have already defined the status code
if (err.statusCode){
// In production, you'd want to make sure that err.message is 'safe' for users to see, or else use a different value there
return res.status(err.statusCode).json({ message: err.message });
}
return res.status(500).json({ message: 'An error has occurred, please contact the system administrator if it continues.' });
});
请注意,Express 中的几乎所有内容都是通过中间件完成的。