javascript - 如何打印从 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"
解决方案
我现在通过拆分收到的字符串找到了解决方案,直到只剩下消息和代码之间的部分(返回我要打印的错误消息)。
let innerError = error.response.data.message;
innerError = innerError.split('content:\n')[1];
innerError = innerError.split('message=').pop().split(',code=')[0];
console.log(innerError);
但是,这远非一个干净的解决方案,所以如果有人愿意提供,我仍在寻找输入。
推荐阅读
- mysql - 这是我在 MySQL 中的代码。我不断收到错误 #1064
- laravel - doc、docx、pdf、csv xls、xlsx 扩展在 livewire laravel 中不起作用 - 此驱动程序不支持创建临时 URL
- python - tkinter 使用树莓派 GPIO 更改帧
- flutter - 即使浮动,SliverAppBar 也不会跟随用户的手势:true
- node.js - 如何验证密钥对匹配?(节点锻造)
- python - 判断一个数是否是回文数
- c# - SerialPort 写入所用时间
- python - 减少我的代码在 python 中计算股票指标的时间
- javascript - 在从 React 中的 API 调用获取实际数据之前从状态中获取空值
- google-cloud-platform - gcp free tier 如果您超过或使用非免费的东西会发生什么