【问题标题】:How describe with typescript axios request如何使用打字稿 axios 请求进行描述
【发布时间】:2021-12-02 22:18:56
【问题描述】:

我对 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 请求、错误

【问题讨论】:

    标签: reactjs typescript axios


    【解决方案1】:

    您想要对 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
      }
    }
    

    您现在可以添加适当的逻辑来处理您的错误并返回有效的东西:)

    【讨论】:

    • 据我了解,要在 catch 块中描述错误类型,我们需要使用 ant 类型吗?如果我们得到的错误不是来自 try catch 块而是来自 interseptors,那么 axios interseptors 呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 2018-08-23
    • 2016-11-17
    • 2022-08-12
    • 2019-10-10
    • 2020-09-02
    相关资源
    最近更新 更多