Error Handling#
If your query or mutation happens to throw an error when using fetchBaseQuery, it will be returned in the error property of the respective hook.
tip
If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
Errors with a custom baseQuery#
By default, RTK Query expects you to return two possible objects:
- Expected success result format
- Expected error result format
note
This format is required so that RTK Query can infer the return types for your responses.
As an example, this what a very basic axios-based baseQuery utility could look like:
- TypeScript
- JavaScript
Ultimately, you can choose whatever library you prefer to use with your baseQuery, but it's important that you return the correct response format. If you haven't tried fetchBaseQuery yet, give it a chance!
Retrying on Error#
RTK Query exports a utility called retry that you can wrap the baseQuery in your API definition with. It defaults to 5 attempts with a basic exponential backoff.
The default behavior would retry at these intervals:
- 600ms * random(0.4, 1.4)
- 1200ms * random(0.4, 1.4)
- 2400ms * random(0.4, 1.4)
- 4800ms * random(0.4, 1.4)
- 9600ms * random(0.4, 1.4)
- TypeScript
- JavaScript
In the event that you didn't want to retry on a specific endpoint, you can just set maxRetries: 0.
info
It is possible for a hook to return data and error at the same time. By default, RTK Query will keep whatever the last 'good' result was in data until it can be updated or garbage collected.
Bailing out of errors#
retry.fail
Handling errors at a macro level#
There are quite a few ways that you can manage your errors, and in some cases, you may want to show a generic toast notification for any async error. Being that RTK Query is built on top of Redux and Redux-Toolkit, you can easily add a middleware to your store for this purpose.
tip
Redux-Toolkit released matching utilities in v1.5 that we can leverage for a lot of custom behaviors.
- TypeScript
- JavaScript