我對 axios 請求進行了 thunk 操作,但是當我收到錯誤而不是請求時它失敗了,因為在我的減速器下面等待 IUser 型別的資料,但從服務器收到了錯誤訊息
我的代碼:
export const checkAuth = createAsyncThunk(
`authService/checkAuth`,
async (prevLocation:string) => {
const response = await axios.get<IUser>('/api/auth/current')
return {user:response.data, isAuth: true}
}
)
問題:如何正確處理 axios 請求、錯誤
uj5u.com熱心網友回復:
您想要對 async/await 代碼做的是始終實作 try/catch 塊,這樣不會發生這樣的情況,并且錯誤將得到正確處理。
async () => {
let response; // properly typed
try {
response = await axios.get<IUser>('/api/auth/current')
} catch(ex) {
console.log(ex) // handle exception
}
}
您現在可以添加適當的邏輯來處理您的錯誤并回傳有效的內容:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315134.html
下一篇:打字稿中的pick<>陣列型別
