【问题标题】:React - FC - How to stop execution in react environmentReact - FC - 如何在反应环境中停止执行
【发布时间】:2021-11-20 11:06:15
【问题描述】:

目前我有一个 React + Redux 应用程序。 我想在任何 API 调用失败时停止执行。我使用 axios 调用 API。 我试图通过在 axios 拦截器中抛出错误来停止执行。

    axiosInstance.interceptors.response.use(
          (response: AxiosResponse) => response,
           async (failedRequest: iFailedRequest) =>
                 apiErrorHandler(failedRequest)
    );

这是我的apiErrorHanlder 方法。

const apiErrorHandler(failedRequest) = () => {
   throw new Error("error") // I want my application execution to stop here without affecting the UI state
}

但问题是在react/JS执行中继续进行到下一行代码。

const MyComponent = ()  => {

const apiCall = async () => {
   await axios.get("/api_end_point") // Stop execution here if API call has been failed
   console.log("success API call") // This should only be printed in case of successful API call
}

useEffect(() => {
   apiCall();
}, [])

return <></>;

}

【问题讨论】:

    标签: javascript reactjs typescript error-handling axios


    【解决方案1】:

    您可以为此使用 try/catch 块:

    文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

    try {
      await axios.get("/api_end_point")
    } catch (error) {
      console.error(error);
    }
    

    【讨论】:

    • 可能是我的方法是错误的,但我想在apiErrorHandler() 中停止执行。有什么办法吗?这样我就不必在每个 API 上都放置 try/catch 块。
    • 通常您需要处理这些错误响应,这也是默认行为。除了将它包装到 try/catch 中或像以前那样抛出错误之外,我没有看到其他方法。
    • 其他方法也需要更多的代码,比如定义一个后备值,以防响应失败并对你的 ui 做出适当的反应。这是我建议的更好方法。这意味着在错误处理程序中返回某种值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多