Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using redirect inside onError results in uncaughtException: Error: NEXT_REDIRECT #109

Closed
awinograd opened this issue Oct 5, 2023 · 2 comments

Comments

@awinograd
Copy link

👋 I'm testing out using this library (migrating from graphq-request) and am wondering how to support a workflow I currently use.

For certain network errors, we want to redirect users. Pseudo-code is something like:

// apollo.ts
export const { getClient } = registerApolloClient(() => {
  return new ApolloClient({
    onError: ({ graphQLErrors, networkError, operation }) => {
        if (isSpecficError(networkError)) {
            console.log('Before redirect')
            redirect('/handle-error')
            console.log("after redirect, never seen");
        }
    },
  })
})
// layout.tsx

export default function Layout() {
    console.log("Layout 1")
    const result = await getClient().query(Query);
    console.log("Layout 2")
    console.log(result)
    return <div />
}
Output:
Layout 1
Before redirect
Layout 2
{ data: null, error: null }
uncaughtException: Error: NEXT_REDIRECT

When the redirect is hit, I'm seeing an uncaughtException rather than nextjs catching the redirect exception and handling it properly. From what I can tell this seems to be a side-effect of the way links/observables work. Perhaps the redirect isn't thrown in the correct execution stack for next to catch it properly. Is there a way to set up apollo client such that nextjs can handle navigation errors such as redirect/notFound?

@phryneas
Copy link
Member

phryneas commented Oct 6, 2023

I think not with onError, as that will happen in parallel and not "in a line" with your promise.

Generally, to my knowledge network errors are handled centrally in Apollo Client, and will usually not make it into your result - the line of thinking here is that you should not need to handle something like a connection loss in every individual page, but only in one central place.

You could try errorPolicy: "all", in which case errors would make it into the result and could be handled there, but I'm not 100% sure if network errors will make it in there.

@awinograd
Copy link
Author

Thanks for your thoughts @phryneas . errorPolicy: all does not make a difference so sounds like this type of behavior is not supported / possible. Feel free to consider this closed if you'd like. I'll stick to using graphql-request for RSC funtionality

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants