javascript - 捕获块不会被解雇
问题描述
我有一个 API 的异步调用,其中第二个 .catch 块没有被执行。
我在 utils 文件中定义了主要的 API 调用函数,如下所示:
const getCustomer= (body) => {
return new Promise(resolve => {
fetch('/getCustomer', {
method: 'post',
body: JSON.stringify(body),
headers: {
Accept: "application/json"
Content-type: "application/json"
- },
})
.then(response => response.json())
.then(json => resolve(json))
.catch(err => console.log('error happened', err))
})
};
稍后在我的 JSX 文件中,我通过导入上面的函数来调用 API。
getCustomer(myPayload).then(res => {
setCustomer(res)
}).catch(err => {
setShowError(true)
})
我想要做的是使用 setShowError 显示错误消息,但由于某种原因,我只能看到console.log('error happened', err)
从 utils 文件夹中抛出的信息,我在其中定义了我的 fetch 函数。关于如何解决此行为并执行 catch 功能的任何想法
解决方案
如果您希望两个.catch
es 都执行,则需要将第一个放入其中,否则结果将getCustomer
始终返回一个可解析的 Promise。您还需要使用reject
Promise 构造函数的参数。
new Promise((resolve, reject) => {
// ...
.catch(err => {
console.log('error happened', err);
reject(err);
})
并确保在你的 React 代码中返回 Promise 调用:
return setCustomer(res);
虽然这是可能的,但如果可行,通常更好的方法是不捕获下面的错误,而是让调用者处理它。也不要使用显式的 Promise 构造反模式。
const getCustomer= (body) => {
return fetch('/getCustomer', {
method: 'post',
body: JSON.stringify(body),
headers: {
Accept: "application/json"
Content-type: "application/json"
- },
})
.then(response => response.json());
};
是我更喜欢的。除非你真的需要它setCustomer
自己来处理它,否则让错误渗透到它的调用者。
推荐阅读
- c# - 监听来自编辑器脚本的键输入
- javascript - Angular IE11 文件上传取消事件
- css - 如何在没有/deep/的情况下覆盖`ng-template`构建字段的css样式?
- javascript - JavaScript中的地理位置不返回位置
- ftp - 对 ALLO 的否定响应的 lftp 处理
- java - 如何使用 Java SQL API 重命名 Azure Cosmos DB 中的容器?
- batch-file - 如何批量输入密码?
- android - Dart FFI - 从 C++ 调用 Dart 函数
- database - 如何为来自 ORM 系统(用于 PHP)的字段构建带有翻译的表单?
- r - 展开表格中的变量标签