无法从 inversify-express-utils 控制器全局捕获错误
Unable to catch errors globally from inversify-express-utils controllers
我正在使用这个包 https://github.com/inversify/inversify-express-utils for a nodejs app, and I want to have a place to handle errors from any controller, the way I know is to use express error handler,
但在这种情况下它似乎不起作用 - 没有人调用错误处理程序:
userController.ts
import {interfaces, controller, request, response, httpGet} from "inversify-express-utils";
@controller('/user')
class UserController implements interfaces.Controller {
....
@httpGet('/')
private async get(@request() req, @response() res) {
throw new Error('BROKEN!');
}
}
server.ts
....
const server = new InversifyExpressServer(container);
server.setConfig((app) => {
...
app.use((err, req, res, next) => {
console.log(err); // This never called
});
return app;
});
- 为什么处理程序没有被调用?
- 使用 inversify-express 包有更优雅的方法吗?
你应该在初始化服务器时使用setErrorConfig
,像这样:
server.setErrorConfig((app) => {
app.use((err, req, res, next) => {
if (err) {
if (err instanceof HttpRedirectError) {
return res.redirect(err.redirectUrl);
}
return res.json(Requester.createError(err));
}
next();
});
});
我正在使用这个包 https://github.com/inversify/inversify-express-utils for a nodejs app, and I want to have a place to handle errors from any controller, the way I know is to use express error handler, 但在这种情况下它似乎不起作用 - 没有人调用错误处理程序:
userController.ts
import {interfaces, controller, request, response, httpGet} from "inversify-express-utils";
@controller('/user')
class UserController implements interfaces.Controller {
....
@httpGet('/')
private async get(@request() req, @response() res) {
throw new Error('BROKEN!');
}
}
server.ts
....
const server = new InversifyExpressServer(container);
server.setConfig((app) => {
...
app.use((err, req, res, next) => {
console.log(err); // This never called
});
return app;
});
- 为什么处理程序没有被调用?
- 使用 inversify-express 包有更优雅的方法吗?
你应该在初始化服务器时使用setErrorConfig
,像这样:
server.setErrorConfig((app) => {
app.use((err, req, res, next) => {
if (err) {
if (err instanceof HttpRedirectError) {
return res.redirect(err.redirectUrl);
}
return res.json(Requester.createError(err));
}
next();
});
});