michaelschufi
michaelschufi2mo ago

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:
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() 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?
0 Replies
No replies yetBe the first to reply to this messageJoin