您通常不希望在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.' });
});
注意,几乎一切都在快速通过中间件来完成。
你能显示一些代码吗?做下一步(err)会产生什么样的结果?我的大部分api都没有中间件,下一步(err)还是相关的? –
你推荐什么中间件来处理错误? –
我展示的那个?节点中的中间件只是一个处理函数。有时你可以通过使用模块来实现,但是你不需要。我写了praeter(https://www.npmjs.com/package/praeter)作为包装我提到的上述内容的一种方式,但您可以使用自己的代码轻松完成。 – Paul