[英]How describe with typescript axios request
I have thunk action with axios request but it's failed when instead of request I get error because below my reducer wait for data with IUser types but instead got error messages from server我对 axios 请求进行了 thunk 操作,但是当我收到错误而不是请求时它失败了,因为在我的减速器下面等待 IUser 类型的数据,但是却收到了来自服务器的错误消息
My code:我的代码:
export const checkAuth = createAsyncThunk(
`authService/checkAuth`,
async (prevLocation:string) => {
const response = await axios.get<IUser>('/api/auth/current')
return {user:response.data, isAuth: true}
}
)
Question: How correctly handle axios request, errors问题:如何正确处理 axios 请求、错误
What you want to do with async/await code is to always implement try/catch blocks, so situations like that won't happen, and the error will be properly handled.您想要对 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
}
}
You can now add proper logic to handle your error and return valid stuff :)您现在可以添加适当的逻辑来处理您的错误并返回有效的内容:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.