首页 > 解决方案 > 捕获块不会被解雇

问题描述

我有一个 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 功能的任何想法

标签: javascriptreactjs

解决方案


如果您希望两个.catches 都执行,则需要将第一个放入其中,否则结果将getCustomer始终返回一个可解析的 Promise。您还需要使用rejectPromise 构造函数的参数。

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自己来处理它,否则让错误渗透到它的调用者。


推荐阅读