我正在使用 Node.js Express 创建一些 HTTP REST API。 我有调用返回 Promise 的下划线 service 的方法,如下所示:
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);
现在,我引入错误处理如下:
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"))
将返回 {}
。要获得与控制台输出相同的结果,您必须将错误对象强制转换为字符串,如下所示:
.catch(function (err) {
console.error('Error occurred in Apps Api: ' + err);
response.status(500).send("" + err);
});
PS:对于内部错误,您应该使用 status(500)
。
编辑
如果这种情况不需要单独的错误处理机制,您可以让 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"));
});
}
如果 express 的默认错误处理没有给你满意的结果,你可以注册你自己的错误处理程序:
...
// 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);
});
关于javascript - Node.js Express,错误处理仅适用于 console.error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39082245/