我对表达还很陌生,想知道是否存在全局错误捕获器。我正在处理一个已经存在的代码,其中创建了所有控制器,并且在所有控制器中实现 try 和 catch 将是菜鸟。我需要一个全局错误捕获器来检测代码中的中断并响应客户端。是否有现有的库或现有的代码实现。
如果您的控制器不是异步的,您可以在注册所有路由后添加错误处理程序
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
throw new Error('Something went wrong');
});
// Add more routes here
// Error handler
app.use(function (err, req, res, next) {
// All errors from non-async route above will be handled here
res.status(500).send(err.message)
});
app.listen(port);
Run Code Online (Sandbox Code Playgroud)
如果您的控制器是异步的,您需要向控制器添加自定义中间件来处理异步错误。中间件示例取自此答案
const express = require('express');
const app = express();
const port = 3000;
// Error handler middleware for async controller
const asyncHandler = fn => (req, res, next) => {
return Promise
.resolve(fn(req, res, next))
.catch(next);
};
app.get('/', asyncHandler(async (req, res) => {
throw new Error("Something went wrong!");
}));
// Add more routes here
// Error handler
app.use(function (err, req, res, next) {
// All errors from async & non-async route above will be handled here
res.status(500).send(err.message)
})
app.listen(port);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4334 次 |
| 最近记录: |