Search code examples
reduxreact-reduxredux-toolkitrtk-query

RTK Query get Status code && error message from Error response


I am using Redux-Toolkit (RTK) Query with custom baseQuery

const staggeredBaseQueryWithBailOut = retry(
  async (args: FetchArgs | string, api, extraOptions) => {
    try {
      const result = await fetchBaseQuery({
        baseUrl: config.apiBaseURL,
        prepareHeaders: (headers, api) => {
          const {
            auth: { token }
          } = api.getState() as RootState
          if (isCustomQuery(args) && args.url === config.authURL) {
            headers.set("Authorization", `Basic ${config.basicToken}`)
          } else {
            if (token) headers.set("Authorization", `Bearer ${token}`)
          }
        }
      })(args, api, extraOptions)
      if (result.error) throw result
      return result
    } catch (error) {
      return { error: error }
    }
  },
  {
    maxRetries: 2
  }
)

Whenever the API call fails, the API responds with errorMessage.

I want to get the errorMessage && the status code.

The error object returning from the useQueryHook is one generated by RTKQ with non-descriptive message like "FETCH_ERROR".

Is there a way around?


Solution

  • It figured out that the problem was with CORS Headers are not sent back in case of error response. just an API issue not an rtk query implementation error.