Errors are supressed in onSuccess callbacks #824
Send to my agentDescribe the bug When an exception is raised in onSuccess callbacks, the error is suppressed
To Reproduce Steps to reproduce the behavior:
async function exampleQueryFunction() {
return "response";
}
const query = useQuery("key", exampleQueryFunction, {
onSuccess: response => {
debugger;
throw new Error("This error should propogate");
},
onError: err => {
console.log(err);
}
});
Expected behavior I expect some indication that there was an error in onSuccess. Definitely expect that isError is set to true, but it is not. I don't think that onError is the right place to handle this because it corresponds to the query function.
Maybe a final onAnyError callback that catches any unhandled exception anywhere ?
Desktop (please complete the following information):
- OS: Ubuntu 18
- Browser: Chrome
- Version: 81.0.4044.138
Additional context Add any other context about the problem here.
tannerlinsley added labelsbug
tannerlinsley removed labelsbug
tannerlinsley added labelsenhancement
tannerlinsley added labelshelp wanted
@mustafawm , not in the way I’d expect. Which is to say that I like having the onerror callback and wouldn’t want to give up on that because of errors in onsuccess.
Like there needs to be a difference between the error my server returned and something stupid I did on the client after the response .
But perhaps onerror and onsuccess should throw in error ?
What's wrong with this?
const query = useQuery("key", exampleQueryFunction, { onSuccess: response => { try { await possiblyJankySideEffect() } catch (err) { console.log('My Bad') } }, onError: err => { console.log(`Server's fault`) } });I think that works, maybe just make the docs more explicit about that. Happy to give it a shot
Reopen if necessary.
tannerlinsley closed this
I'm having a similar problem. The server is returning status 202, as the data is not ready yet. And since 202 is success status, my idea was to return an error in onSucces, and then use the retry with delay when this happens, until the server responds with 200. But I haven't found a way to simulate an error when I have a success status.
you need to return the error from the queryFn:
useQuery( key, async () => { const response = await axios.get(..) if (response.status === 202) { throw new Error("whatever") } return response.data } )callback functions are not the place to do data transformation!
I think that having to add try/catch or else the error just disappears completely is pretty unexpected and easy to fall into traps around, since normally the default behavior for errors thrown and not caught is to at least run the global onError handler and log it to the console. I basically just want all uncaught errors here to get logged to the console and to Sentry. It's a pain to have to add a try/catch to every useQuery (and have to remember to do so), or risk errors that I just never find out about because they're suppressed completely.
I think that having to add try/catch or else the error just disappears completely is pretty unexpected and easy to fall into traps around
I don't understand this. This issue is pretty old, so I'm not sure what exactly you are referring to. To log all errors, you can use the global error handlers on the queryCache:
It would be best if you'd open a new discussion or issue, best with a minimal, reproducible example of what you're struggling with.
@phoenixeliot I agree completely, I was shocked today when I learned that my errors in the onSuccess callback were being swallowed. I actually couldn't believe it, I would have expected them to bubble up and trigger the error boundary to display my fallback. I tried setting the
useErrorBoundaryandonErrorprops to see if these would run after the error occurred in onSuccess, but nope.@tannerlinsley I believe errors in the onSuccess should most definitely not be swallowed and silently suppressed like that. I wish errors in the onSuccess would abide by the useErrorBoundary prop and either throw it globally so my error boundary can catch by default, or else return in the error payload.
My use case is this:
function useHookToRunInitialQueries() { const { storeGlobalState1 } = useGlobalState1() const { storeGlobalState2 } = useGlobalState2() const { storeGlobalState3 } = useGlobalState3() useQuery('/url1', { onSucess: (d) => { storeGlobalState1(d) } }) useQuery('/url2', { onSucess: (d) => { storeGlobalState2(d) } }) useQuery('/url3', { onSucess: (d) => { storeGlobalState3(d) } }) }The storeGlobalState functions internally run a zod parse to verify the response is what I expect from the api and if the validation fails, I had been expecting them to bubble up to my error boundary but it wasn't working at all. I don't want to first set the state, then validate the payload is what I expect, I would rather just check and fail as early as possible, which in this case would be right there in the
onSuccesscallback.try/catch is not a solution because 1) I don't want to include in every useQuery call and 2) I don't want to handle errors in the onSuccess callback, I want my errorBoundary to handle those errors. Essentially onSuccess is a footgun and an untrusthworthy callback because its very difficult to handle errors.
I was shocked today when I learned that my errors in the onSuccess callback were being swallowed. I actually couldn't believe it, I would have expected them to bubble up and trigger the error boundary to display my fallback
I hope you've recovered from that shock.
The reason is quite simple once you understand React Query.
onSuccessruns on a per-observer basis. If you calluseQuerywith the same key multiple times,onSuccessis also executed multiple times. There is only one query in the cache though, so differentonSuccess"results" (error or no error) would contradict each other. This is also the reason why, unlike useMutation, where each invocation has its own cache entry, we cannot await anything returned fromonSuccess.My use case is this
Sorry to say but this is not a use-case, it's an anti-pattern on multiple levels:
React Query is already a global state manager, there shouldn't be a need to sync it to a different state manager. That's state duplication.
It will get out-of-sync if you use
staleTimeand switch the queryKey, becauseonSuccessis tied to a fetch happening, which doesn't happen in this case.The zod parsing should happen in the query function. I have a whole blogpost on that topic: https://tkdodo.eu/blog/type-safe-react-query
Essentially onSuccess is a footgun and an untrusthworthy callback
I tend to agree, it has limited applicability, like animating an element via a ref or syncing something to local component state (which shouldn't be necessary). In your case though, I'm afraid you're just "using it wrong".
@TkDodo sucks that it was so easy to use "wrong". It was practically an invitation to go the route I did (once a query finishes, do this other thing).
And I understand react query has the ability to do global state, but fundamentally it makes queries and users shouldn't be required to change both their query package and global state method to use it. If people just want to use it to make queries, I think that should be allowed, and it does do that better than any other. I use it essentially as a hooked version of axios. Maybe updating it's state / cache isn't as ergonomic as other state management solutions or they just simply prefer to use something else?
Either way, thank you for the suggestion to do zod parsing in the query which I suppose is the main issue here as errors are the whole point of zod and I would like them as early as possible. Reluctantly, I will still set state into my favorite global statement solution in the onSuccess (as opposed to say a useeffect that listens for data changes and then updates there), Ill just try to remember to add zero logic above simply calling a setstate function.
Thank you also for quick response and I'll be seeing what else I can learn from your blog.
Sign in to join this conversation.
throwOnErrorconfig flag, which is available foruseMutateandqueryCache.prefetchQuerywould solve the issue here.I'm not sure why it's not available for
useQuery🤔