trpc icon indicating copy to clipboard operation
trpc copied to clipboard

Return errors to links correctly

Open goknsh opened this issue 3 years ago • 4 comments

A fix for TRPCErrors thrown on the server arriving in next instead of error in links.

I think this is clearer that the text above:

const customLink: TRPCLink<AppRouter> = (runtime) => {
  return ({ next, op }) => {
    return observable((observer) => {
      const unsubscribe = next(op).subscribe({
        next(value) {
          // `TRPCError`s from the server are sent here
          observer.next(value);
        },
        error(value) {
          // instead of here
          observer.error(value);
        },
        complete() {
          observer.complete();
        }
      });
      return unsubscribe;
    });
  };
};

export const client = createTRPCClient<AppRouter>({
  fetch(url, options) {
    return fetch(url, { ...options, credentials: 'include' });
  },
  transformer: superjson,
  links: [
    customLink,
    httpBatchLink({
      url: '/trpc'
    })
  ]
});

export const proxy = createTRPCClientProxy(client);

I'm pretty sure I got the fix working for httpBatchLink and httpLink, but not 100% sure what I did for wsLink actually works.

goknsh avatar Jul 25 '22 01:07 goknsh

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated
next-prisma-starter ✅ Ready (Inspect) Visit Preview Aug 8, 2022 at 5:42PM (UTC)
www ✅ Ready (Inspect) Visit Preview Aug 8, 2022 at 5:42PM (UTC)

vercel[bot] avatar Jul 25 '22 01:07 vercel[bot]

Will send you some money for the trouble if you setup github sponsors @goknsh

KATT avatar Jul 25 '22 20:07 KATT

Will send you some money for the trouble if you setup github sponsors @goknsh

Sure, I'll try and set it up. fb5dbee378794e799c2910f449f3eba3e46c9bfa adds tests for httpLink and httpBatchLink with an attempt at tests for wsLink. I can't figure out how to get the wsLink test to work. I'll give it another go tomorrow.

goknsh avatar Jul 25 '22 21:07 goknsh

Got it figured out, @KATT I think it's ready to merge, just give the tests a once-over. Also, I thought that the complete function on the client subscription would get called after unsubscribing, but turns out that's not the case; i.e. I thought this line should have been expect(subCompleteFunction).toHaveBeenCalledTimes(1);, but that fails. Is this correct behavior?

goknsh avatar Jul 25 '22 23:07 goknsh

This should now be fixed by #2402

KATT avatar Aug 10 '22 23:08 KATT

This pull request has been locked because it had no new activity for 30 days. If you think, this PR is still necessary, create a new one with the same branch. Thank you.

github-actions[bot] avatar Oct 04 '22 12:10 github-actions[bot]