Error Handling with React Query
Wanted to ask something about error handling using React Query. Novice question but wanted to understand the inner working + if I am going right about this.
All the examples I have seen of it being used are something along the lines of
I have almost never seen React Query functions being wrapped in a try catch or a fetch.then.catch block. They're generally a
fetch().then()
line of code only.
Am I right in saying you don't need to do that with React query since the isError thing handles Errors for you? Or am I missing something on top of this?4 Replies
rare-sapphire•10mo ago
We would need to use
try..catch
or .catch
in above example because in most cases we will handle error with custom error message or some additional logic. But when we do that, we need to make sure we throw error again at the end of the catch block so that the React Query knows the queryFn failed or there was some error executing the query.other-emerald•10mo ago
If your queryFn throws, it's automatically caught.
This changes isError to true, and error is put on the error property.
{ isError, error } = useQuery
You don't need to write a try/catch for a simple fetch. Because it's already caught.
fair-rose•10mo ago
how to set a global error catching and show something like a toast.
for example, if I made a query like this:
I want to define error handling in one place that catches 404 error and shows a toast.
other-emerald•10mo ago
React Query Error Handling
After covering the sunshine cases of data fetching, it's time to look at situations where things don't go as planned and "Something went wrong..."