【问题标题】:How can I print a nested error message returned from REST?如何打印从 REST 返回的嵌套错误消息?
【发布时间】:2019-04-03 11:35:43
【问题描述】:

我目前正在尝试使用 Javascript 打印嵌套错误,但是我似乎只将内部消息作为字符串:

axios.post('http://localhost:8080/axios, data)
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error.response.data.message);
});

status 500 正在读取 Api#create(String,String,Request);内容: {"timestamp":"2018-10-30T12:08:40.524+0000","status":500,"error":"Internal Server Error","message":"EntityStateError[message=这是我的实际错误我要打印。,code=400,service=Service,embeddedErrors=]\r\n","path":"/axios"}

我只想在消息之后打印错误(“这是我的实际错误...”)。

我认为我可以将其解析为 JSON,但是当我使用时

console.log(JSON.parse( '"' + error.response.data.message + '"'));

我收到以下错误:

Uncaught (in promise) SyntaxError: Unexpected token 在 JSON.parse() 的位置 97 处的 JSON 中

如何访问错误响应中的实际消息?

error.response.data 本身:

{timestamp: "2018-10-30T13:31:09.097+0000", status: 500, error: "Internal Server Error", message: "status 500 reading Api#create/axios"}", path: " /axios"} 错误:“内部服务器错误” 消息:“状态 500 正在读取 Api#create(String,String,Request);内容:↵{"timestamp":"2018-10-30T13:31:09.076+0000","status":500,"error":"内部服务器错误","message":"EntityStateError[message=这是我要打印的实际错误。,code=400,service=Cancellation,embeddedErrors=]\r\n","path":"/ axios"}" 路径:“/axios” 状态:500 时间戳:“2018-10-30T13:31:09.097+0000”

【问题讨论】:

  • 你能从控制台分享错误响应数据吗?
  • @TiisetsoTjabane,我已将error.response.data的控制台日志添加到问题的底部。

标签: javascript rest axios


【解决方案1】:

我现在找到了一个解决方案,将收到的字符串拆分,直到只剩下消息和代码之间的部分(返回我要打印的错误消息)。

let innerError = error.response.data.message;
innerError = innerError.split('content:\n')[1];
innerError = innerError.split('message=').pop().split(',code=')[0];

console.log(innerError);

但是,这远不是一个干净的解决方案,所以如果有人愿意提供,我仍在寻找意见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 2018-07-09
    • 2019-04-24
    • 1970-01-01
    • 2020-05-01
    相关资源
    最近更新 更多