更新时间:2022-06-11 22:46:18
最新版本的Express使用智能默认错误处理程序。
The latest version of Express use smart default error handler.
在开发
模式下,它发送完整堆栈追溯到浏览器,而在生产
模式中,它只发送 500内部服务器错误
。
In development
mode it sends full stack trace back to the browser, while in production
mode it sends only 500 Internal Server Error
.
为了利用它,您应该在运行应用程序之前设置正确的 NODE_ENV
。
To take advantage of it you should set proper NODE_ENV
before running your application.
例如,要在生产模式下运行应用程序:
For example, to run your app in production mode:
NODE_ENV=production node application.js
但是,如果您不喜欢此默认行为,您可以定义自己的错误处理程序:
But if you don't like this default behavior, you could define your own error handler:
app.use(function(err, req, res, next){
console.error(err);
res.status(500);
res.render('error');
});
请注意,错误处理程序必须是链中的最后一个中间件,因此应该在底部定义您的 application.js
文件。
Note that error handler must be the last middleware in chain, so it should be defined in the bottom of your application.js
file.
如果您需要更多信息,请参阅:
If you need more information, see: