【问题标题】:How to pass error in a catch once a promise has resolved?承诺解决后如何在 catch 中传递错误?
【发布时间】:2021-01-02 15:09:22
【问题描述】:

我有一个 api 调用。万一它失败了,我想得到一个错误。为什么错误出现在then()中而不是catch()中?如何从 catch 访问它?我宁愿不必在 then() 中编写长函数,例如 if !res && 等。

代码如下:

const postStuff = async () => {
  try {
    const res = await ax.post("/stuff");
    return res;
  } catch (err) {
    return new Error();
  }
};

export default function App() {
 React.useEffect(()=> {
    postStuff()
    .then(res=> console.log("res", res))
    .catch(err=> console.log("err", err))
 }, [])
  return (
    <div className="App">
     hello world
    </div>
  );
}

【问题讨论】:

  • 为什么将错误从ax.post() 捕获到throw(而不是return ...)另一个错误?
  • 因为我可以在一个地方处理我的错误,而不必每次在应用程序中使用此功能时重复一段代码。这样更容易。

标签: javascript reactjs asynchronous error-handling promise


【解决方案1】:

由于您只是在捕获错误后返回错误,因此它将不再到达 useEffect 内的 catch 块。

只需在 catch 块中抛出错误:

const postStuff = async() => {
  try {
    const res = 'bla';
    throw new Error();
    return res;
  } catch (err) {
    throw new Error();
  }
};

postStuff().then(res => console.log('then', res))
  .catch(err => console.log('catch', err))

或者去掉postStuff中的try catch:

const postStuff = async() => {
  const res = 'bla';
  throw new Error();
  return res;
};

postStuff().then(res => console.log('then', res))
  .catch(err => console.log('catch', err))

【讨论】:

    【解决方案2】:

    您需要抛出错误,而不是从 postStuff catch 块内部返回

    
     const postStuff = async () => {
      try {
        const res = await ax.post("/stuff");
        return res;
      } catch (err) {
        throw new Error();
      }
    }; 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 2019-01-08
      • 2021-06-11
      • 2015-12-08
      • 2016-04-05
      • 1970-01-01
      • 2020-09-07
      相关资源
      最近更新 更多