【发布时间】:2020-07-15 07:35:06
【问题描述】:
我正在开发 React Redux 应用程序,
我收到 “Uncaught (in promise) TypeError: error.json is not a function” 错误,同时尝试从返回的 API 错误中破坏错误消息。我的 API 返回错误,结构如下:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|5f13e001-48d7893e3cc8e8ff.",
"errors": {
"Code": [
"'Code' must not be empty."
],
"Name": [
"'Name' must not be empty."
]
}
}
这是我处理保存方法的方式:
const handleSave = (event) => {
event.preventDefault();
setSaving(true);
saveTeam(team)
.then(() => {
showSnackbar("Team was saved successfully");
history.push("/teams");
})
.catch((error) => {
let errorMessage = error.message.json();
debugger;
setErrors({ onSave: error.message }); //<---- In here I want to pass just the list of errors
setSaving(false);
});
};
我遇到了这个异常:
Uncaught (in promise) TypeError: error.message.json is not a function
顺便说一句。我将error.message 传递给SetErrors,然后我将其打印在屏幕上。这就是我得到的:
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|5f13e004-48d7893e3cc8e8ff.","errors":{"Code":["'Code' must not be empty."],"Name":["'Name' must not be empty."]}}
所以error.message 就是我要找的……但我怎样才能破坏它呢?
【问题讨论】:
-
如果
errors.message返回您正在显示的对象 -{"type": ...},那么如果它还不是JavaScript对象,您应该使用JSON.parse,或者只是选择您想要的任何属性错误信息,例如error.title -
你能澄清为什么你特别试图在错误时执行 json() 吗?什么给你的印象是它应该有一个 json() 方法?如果你只是 console.log(error) 会发生什么?
-
@AlexanderStaroselsky 我想获取错误列表。 console.log(error.message) 打印一个 json 格式的字符串
-
好的,如果你 console.log(error.message) 什么会注销?你为什么要执行一个方法 json()?
-
@IshThomas 你试过用
JSON.parse(error.message)把JSON变成一个普通的JavaScript对象,这样你就可以获取你需要的任何属性了吗?
标签: javascript json reactjs redux async-await