![](/img/trans.png)
[英]React.JS + axios parsing error in initialState. Axios is installed
[英]not able to catch error in axios react.js
我在 reactjs 項目中使用 axios 進行 API 調用,但不知何故我無法捕獲錯誤。 我得到404但無法捕捉到它。 有人能告訴我怎么了嗎?
abc.js
export default axios.create({
baseURL: `my_base_url`,
headers: {
"Content-Type": "application/json",
},
});
xyz.js
export const createProcessApiCall = (param) => {
return API.post("/v1/process1", param);
};
zzz.js
const postData = async (param) => {
await createProcessApiCall(param)
.then((response) => {
setApiData(response.data.data);
setIsSuccess(response.data.isSuccess);
})
.catch((e) => {
setIsError(true);
});
};
您正在將異步代碼與同步代碼結合使用,請嘗試使用異步代碼:
const postData = async (param) => {
try {
const result = await createProcessApiCall(param)
}
catch(err) {
setIsError(true);
}
};
或同步:
const postData = (param) => {
createProcessApiCall(param)
.then((response) => {
setApiData(response.data.data);
setIsSuccess(response.data.isSuccess);
})
.catch((e) => {
setIsError(true);
});
};
任何包含在 200-299 之間的不同序列的狀態碼,你需要在 catch 中獲取:
const postData = async (param) => {
await createProcessApiCall(param)
.then((response) => {
setApiData(response.data.data);
setIsSuccess(response.data.isSuccess);
})
.catch((e) => {
// @TODO parse err
console.log(e.response);
setIsError(true);
});
};
axios.interceptors.response.use(res=>{return res}, (error) => {
if (error.response.status !== 401) {
throw error;
}
if (typeof error.response.data.error.name !== "undefined") {
//do something on the error
}
});
最好使用 axios 攔截器來捕獲錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.