【问题标题】:Node.js Express, Error handling works only with console.errorNode.js Express,错误处理仅适用于 console.error
【发布时间】:2016-12-29 03:57:37
【问题描述】:

我正在使用 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 并且正文是空的,它只包含大括号:

{}

【问题讨论】:

  • 你是真的扔,还是apps是空的?
  • .stack 是错误 afaik 的不可枚举属性,这意味着它将被 send 忽略。而且您不希望它被发送给用户?
  • @Bergi 完成,道歉

标签: javascript node.js express promise


【解决方案1】:

像这样删除状态 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);
  });
}

【讨论】:

  • 但是您的解决方案返回 200,这在 REST 中是错误的,这是一个错误,所以我必须返回 400 或 500
【解决方案2】:

这是因为错误对象没有可枚举的属性,所以JSON.stringify(new Error("my message"))会返回{}。要获得与控制台输出相同的内容,您必须将错误对象 coerect 为字符串,如下所示:

.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);
});

【讨论】:

    猜你喜欢
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2014-12-15
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多