javascript - 在 fetch 调用中使用响应正文引发自定义错误
问题描述
我想知道如何创建自定义错误处理,我将在其中获取已解析的响应主体并将其传递给 fetch 函数中的自定义错误。在我的示例中,我收到响应正文中许多字段的验证错误。这是一个例子:
class ValidationError extends Error {
constructor(resBody, ...params) {
super(...params);
this.name = 'ValidationError';
this.body = resBody.json();
}
}
这是 fetch 函数:
return fetch(
`${this.formUrl(id)}/status`,
{
method: 'PATCH',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(jsonBody)
})
.then((res) => {
if (res.ok) {
return res.json();
}
if (res.status === 400) {
throw new ValidationError(res.body);
} else {
throw new Error(`http failed: ${res.status} ${res.statusText}`);
}
});
然后我在我的组件中使用它:
.then(() => {
this.setState({navigateTo: '/'})
}).catch(error => {
this.setState({error});
})
但是,这失败res.body
了,因为那时是readableStream
。我该如何解决这个问题,以便我可以error types
根据response status
我的fetch
功能设置不同的,我可以在哪里使用resolved response body
?
解决方案
迟到的回复。但希望它可以帮助其他人搜索相同的问题。
我们需要检查error.response.data以在 catch 块中获取已解析的响应正文。
由于 res.status > 200 会立即在 Promise.then 中抛出一个错误,所以我们需要在 catch 中添加一些东西。
.catch(error => {
if (error.response.status === 400) {
console.log(error.response.data)
} else {
.....
}
})
仍然有一些方法可以获取错误中的详细信息。
- 错误名称
- 错误信息
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
推荐阅读
- entity-framework-core - 使用 Entity.CurrentValues.SetValues 更新导航属性
- python - Vowpal Wabbit - 格式错误的示例,只有一行可以有成本(上下文强盗)
- swift - AR Quick Look - Using double sided Materials in USDZ is not displayed
- podman - 从 Docker 迁移到 Podman
- vue.js - vuex 模块的 npm 包在调度后给出错误
- c# - 使用 Microsoft.CodeAnalysis.CSharp.Scripting 动态执行 C# 失败
- git - 在用户提交后,推送到远程 git 存储库之前,如何通过 sonarqube 分析代码?
- c++ - 如何从 unordered_map 中删除向量元素
- cplex - 是否可以在 CPLEX 中的特定时刻评估累积函数?
- unix - AIX IBM 服务器上的替代截断 cmd