tRPCttRPC
Powered by
Michael SchaufelbergerM
tRPC•2y ago•
1 reply
Michael Schaufelberger

How to access the request body in the onError callback?

Hi 👋

I'm having trouble getting the request's body (probably plain text) when the following error occurs in the
fetchRequestHandler
fetchRequestHandler
:
TRPCError: "input" needs to be an object when doing a batch call
TRPCError: "input" needs to be an object when doing a batch call


I've tried to get it with
req.text()
req.text()
but as it is already consumed, I cannot access it.

The code in question:
fetchRequestHandler({
    endpoint: '/api/trpc',
    req,
    router: appRouter,
    createContext: () => ({}),
    onError: async ({ error, req, input }) => {
      console.log('TRPC route error', error);

      let body = null;

      try {
        if (req.method === 'POST') {
          const isJsonContentType =
            !!req.headers.get('Content-Type')?.includes('application/json') ??
            false;
  
          body = isJsonContentType ? await req.json() : await req.text();
        }
      } catch () {
        // here it would throw that the body is unusable
      }
       
      console.log(
        req.method,
        req.headers.get('Content-Type'),
        { body, input },
       // here: both, body and input are empty 
      );

      // ...
    }
}
fetchRequestHandler({
    endpoint: '/api/trpc',
    req,
    router: appRouter,
    createContext: () => ({}),
    onError: async ({ error, req, input }) => {
      console.log('TRPC route error', error);

      let body = null;

      try {
        if (req.method === 'POST') {
          const isJsonContentType =
            !!req.headers.get('Content-Type')?.includes('application/json') ??
            false;
  
          body = isJsonContentType ? await req.json() : await req.text();
        }
      } catch () {
        // here it would throw that the body is unusable
      }
       
      console.log(
        req.method,
        req.headers.get('Content-Type'),
        { body, input },
       // here: both, body and input are empty 
      );

      // ...
    }
}


I would very much like to know what was sent in order to debug - in any case.
The body has to be forwarded to the callback by tRPC, correct? Or is there another way?
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

onError callback type
MugetsuMMugetsu / ❓-help
2y ago
how to access body in middleware
TaylorFayTTaylorFay / ❓-help
3y ago
How to get the Request Body data of QStash
Rasel HossainRRasel Hossain / ❓-help
2y ago
How to change error message in onError
Answer OverflowAAnswer Overflow / ❓-help
10mo ago