简体   繁体   English

如何使用拦截器全局处理响应

[英]How to use interceptors to handle response globally

I have just started exploring axios and using interceptors我刚刚开始探索 axios 并使用拦截器

In my code, I have axios api call here and there, So I used interceptors to handle error,在我的代码中,我到处都有 axios api 调用,所以我使用拦截器来处理错误,

but it still show uncaught error in my console.但它仍然在我的控制台中显示未捕获的错误。 I dont know why is that?我不知道这是为什么?

For example, this is my api code:例如,这是我的 api 代码:

export const getcountryAllocations = async (country: string) => {
  const response = await instance.get<IcountryAllocationTypeResponse[]>(
    `/asa/${country}`
  )
  return response.data
}

So, in order to handle error in a centralized way, I used interceptors to handle error.所以,为了集中处理错误,我使用了拦截器来处理错误。

export const instance = axios.create()

instance.interceptors.response.use(
  res => {
    return res
  },
  error => {
    if (error.response.status === 401) {
      console.log(error)
    }
    throw error
  }
)

But I still get a red error in console when I get api request error, say the example api I mentioned above但是当我收到 api 请求错误时,我仍然在控制台中收到红色错误,比如我上面提到的示例 api

GET http://localhost:30087/asa/USD 401 (Unauthorized)

AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

localhost/:1 Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

But I expect that it shouldnt display localhost/:1 Uncaught anymore, as I have handled it in interceptors但我希望它不应该再显示 localhost/:1 Uncaught,因为我已经在拦截器中处理过它

You are catching the error but then throwing it again.您正在捕获错误,但随后再次抛出它。 That's why you still have the red error in the console.这就是为什么您在控制台中仍然出现红色错误的原因。

What you can do is catch the error and then return an object saying an error occurred without throwing it again.您可以做的是捕获错误,然后返回 object 表示发生了错误,而不会再次抛出错误。

export const instance = axios.create()

instance.interceptors.response.use(
  res => {
    return res
  },
  error => {
    if (error.response.status === 401) {
      console.log(error)
    }

    return {
      success: false,
      message: error.message,
      status: error.response.status
    }
  }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM