【问题标题】:NodeJs express error middleware parsingNodeJs 表达错误中间件解析
【发布时间】:2019-01-22 15:55:47
【问题描述】:

我正在尝试编写一个中间件来处理错误。但我无法弄清楚如何将正确的格式发送到我的前端。下面我将列出我所有的尝试,希望能帮助你。

尝试 1

app.use(function(err, req, res, next) {
    const formatted = err;
    res.send(formatted)
});

导致邮递员

{ “代码”:422 }

尝试 2

app.use(function(err, req, res, next) {
    const formatted = `${err}`;
    res.send(formatted)
});

结果(邮递员)

错误:请求返回错误代码:422 和正文:{"status":422,"title":"显示名称:build_id 已在此产品上使用。","type":"https://developer.bigcommerce.com/api#api-status-codes" ,"errors":{"display_name":"显示名称:build_id 已在此产品上使用。"}}

这是我想要的数据,但我需要它在 json 中

问题为什么字符串插值后显示的数据更多?如何将其格式化为 json?

【问题讨论】:

  • 我查看了所有这些答案。我需要别的东西。
  • console.log() 的错误不是 JSON,而是文本。我认为您的错误与消息中返回的 bigcommerce 有关
  • 为什么是文字?我知道 API res(当我在邮递员中尝试时)返回 json... 将其转换为某处的文本
  • Error: Request returned error code: 422 and body: {"status":422,"title":"The display name: build_id has already been used on this product.","type":"https://developer.bigcommerce.com/api#api-status-codes","errors":{"display_name":"The display name: build_id has already been used on this product."}} console 遇到的问题,即The display name: build_id has already been used on this product.

标签: javascript node.js express


【解决方案1】:

你可以这样做

app.use(function(err, req, res, next) {
    if (err) {
        res.json({
            status: "error",
            error: `${err}` // <-- edited
        });
    } else {
        next();
    }
});

【讨论】:

  • 如果您查看尝试 1,则只有 { "code": 422 } 直到尝试 2 进行字符串插值。当我尝试这个时,我遇到了同样的问题。只返回代码,不返回消息。
  • @Omar 你能解释一下上下文,比如你发送的请求等,这将有助于我们找到问题。
  • 您是否尝试通过其他平台或任何浏览器发送请求??
【解决方案2】:

如果我不得不猜测,您可能正在寻找res.json(err)

https://expressjs.com/en/api.html#res.json

编辑:完整示例:

app.use(function(err, req, res, next) {
    if (err) res.json(err)
});

【讨论】:

  • 这给了我 json 但不是完整的信息...见attempt 5(刚刚添加)
  • 你还是做错了。我会更新我的答案以更清楚。
  • 这不是重新调整完整的消息。 &gt;{"code": 422 }... 看看尝试一和二的区别。这是我需要弄清楚的问题
猜你喜欢
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 2020-07-11
相关资源
最近更新 更多