我正在使用React Redux应用程序
我正在尝试从返回API错误中破坏错误消息时,出现“未捕获(承诺)TypeError:error.json不是函数” 错误。我的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
是我想要的...但是我怎么破坏它?
答案 0 :(得分:1)
您将收到错误消息,因为仅您的json
对象没有function
类型的属性可以调用
您可以像这样破坏json对象
var jsonob={
"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 {type,title,status,traceId,errors}=jsonob
console.log(type,title,status,traceId,errors)
答案 1 :(得分:1)
假设error.message
实际上是JSON
,则应使用JSON.parse
将JSON
字符串解析为JavaScript
对象:
const error = {
message: JSON.stringify({
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."]
}
})
};
console.log(error.message);
// use destructing assignment to unpack properties from the object
const { type, title, status } = JSON.parse(error.message);
console.log("");
console.log("type", type);
console.log("title", title);
console.log("status", status);
回到您的代码,它应如下所示:
const handleSave = event => {
event.preventDefault();
setSaving(true);
saveTeam(team)
.then(() => {
showSnackbar("Team was saved successfully");
history.push("/teams");
})
.catch(error => {
const { errors } = JSON.parse(error.message);
let allErrors = [];
for (const [key, array] of Object.entries(errors)) {
// use `spread syntax` to combine all error messages
allErrors = [...allErrors, ...array]
}
setErrors({ onSave: allErrors.join(";") });
// 'Code' must not be empty.;'Name' must not be empty.
setSaving(false);
});
};
参考: