首页 > 解决方案 > 如何打印从 REST 返回的嵌套错误消息?

问题描述

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

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

状态 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 in JSON at position 97 at JSON.parse ()

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

error.response.data 本身:

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

标签: javascriptrestaxios

解决方案


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

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

console.log(innerError);

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


推荐阅读