【发布时间】: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