onResponseError doesn't work in useFetch nuxt3

240 views Asked by At

I have a query that retrieves account data

 async fetchAccountProfileData () {
      try {
        const { data, error, execute } = await useApiFetch(
          'api/partner/profile',
          {
            method: 'GET'
          }
        )
        if (error.value?.statusCode === 401) {
          execute()
        }
        if (error.value) {
          throw new Error(error.value.data.message)
        }
        this.PartnerProfile = data.value
      } catch (error) {
        return Promise.reject(error)
      }
    },

Here is the wrapper for all queries for the application

export const useApiFetch = <T>(
  url: string,
  options: UseFetchOptions<T> = {}
): any => {
  const config = useRuntimeConfig()
  const { accessToken } = storeToRefs(useAuthStore())

  options.baseURL = config.public.apiBaseUrl
  options.key = url

  return useFetch(url, {
    ...options,
    server: false,
    lazy: false,
    onRequest ({ options }: { options: any }) {
      options.headers = options.headers || {}
      if (accessToken.value) {
        options.headers.authorization = `Bearer ${accessToken.value}`
      }
    },
    onResponseError: async ({
      response
    }: {
      response: any
    }) => {
      if (response.status === 401) {
        const store = useAuthStore()
        await store.refreshTokenAuth()
      }
    }
  })
}

The problem is that onResponseError does not work in any case, it is simply ignored even if you break the url on purpose. Ыo I can't catch the 401 error.

I have updated nuxt3 to the latest version (3.8.1); I tried using $fetch/ofetch instead of useFetch unfortunately, nothing works.

0

There are 0 answers