Node.js Express,error handling仅适用于console.error
我正在使用Node.js Express来创build一些HTTP REST API。 我有方法调用一个下划线服务 ,返回一个Promise如下:
function getAllApps(request, response) { appService.getAllApps(request.query.$expand).then(function (apps) { response.status(200).send(apps); }) }
我把这个方法映射如下:
var api = express.app; api.get('/apps', getAllApps);
现在,我已经介绍了error handling如下:
function getAllApps(request, response) { appService.getApps(request.query.$expand).then(function (apps) { response.status(200).send(apps); }) .catch(function (err) { console.error('Error occurred in Apps Api: ' + err); response.status(400).send(err); }); }
哪一个按预期工作,除了当遇到一个错误,我得到在控制台的完整的错误堆栈如下:
Express is listening on 127.0.0.1:3000 Web Api ready Error occurred in Apps Api: Error: Actions is not defined on the model.
但是,我的HTTP方法返回400,正文是空的,它只包含大括号:
{}
它是由错误对象不具有枚举属性,所以JSON.stringify(new Error("my message"))
将返回{}
。 要获得与控制台输出相同的结果,必须将错误对象同步到一个string,如下所示:
.catch(function (err) { console.error('Error occurred in Apps Api: ' + err); response.status(500).send("" + err); });
PS:你应该使用status(500)
来解决内部错误。
编辑
如果这种情况不需要单独的error handling机制,可以让express来处理你的错误:
function getAllApps(request, response, next) { appService.getApps(request.query.$expand).then(function (apps) { response.status(200).send(apps); }) .catch(function (err) { next(err || new Error("Unknown error")); }); }
如果明确的“默认error handling不能给你满意的结果,你可以注册自己的error handling程序:
... // note that the middleware having 4 parameters makes it an error handler app.use(function(err, req, res, next) { console.error('Error occurred in Apps Api: ' + err); response.status(500).send("" + err); });
移除状态400,如下所示:
function getAllApps(request, response) { appService.getApps(request.query.$expand).then(function (apps) { response.status(200).send(apps); }) .catch(function (err) { console.error('Error occurred in Apps Api: ' + err); response.json('Error occurred in Apps Api: ' + err); }); }