JavascriptMick
JavascriptMick12mo ago

Use onError to change an application error into a TRPCError?

I want to use the onError handler to change any instance of a custom application error into a TRPCError (I want the HTTP Status code to be a 401 rather than a 500). I tried this but it doesn't work...
onError({error}) {
if (error instanceof AccountLimitError){
error = new TRPCError({ code: 'UNAUTHORIZED', message:error.message })
}
}
onError({error}) {
if (error instanceof AccountLimitError){
error = new TRPCError({ code: 'UNAUTHORIZED', message:error.message })
}
}
nor does this
onError({error}) {
if (error instanceof AccountLimitError){
const trpcError = new TRPCError({ code: 'UNAUTHORIZED', message:error.message })
error = Object.assign(error, trpcError)
}
}
onError({error}) {
if (error instanceof AccountLimitError){
const trpcError = new TRPCError({ code: 'UNAUTHORIZED', message:error.message })
error = Object.assign(error, trpcError)
}
}
I can set individual properties on the error object like error.message but thought there might be an easier way. Has anybody got a nifty hack for this?
5 Replies
Alex / KATT 🐱
Alex / KATT 🐱12mo ago
Error Formatting | tRPC
The error formatting in your router will be inferred all the way to your client (& React components)
Nick
Nick12mo ago
Thrown errors automatically get wrapped with a TRPCError and sent to the frontend Like Alex said, an error formatter is probably what you want if you need to manipulate them
JavascriptMick
JavascriptMick12mo ago
ah nice, thanks guys, yep this works.....
const t = initTRPC.context<Context>().create({
errorFormatter: (opts)=> {
const { shape, error } = opts;
if (!(error.cause instanceof AccountLimitError)) {
return shape;
}
return {
...shape,
data: {
...shape.data,
httpStatus: 401,
code: 'UNAUTHORIZED'
},
};
}
})
const t = initTRPC.context<Context>().create({
errorFormatter: (opts)=> {
const { shape, error } = opts;
if (!(error.cause instanceof AccountLimitError)) {
return shape;
}
return {
...shape,
data: {
...shape.data,
httpStatus: 401,
code: 'UNAUTHORIZED'
},
};
}
})
JavascriptMick
JavascriptMick12mo ago
GitHub
nuxt3-boilerplate/trpc.ts at master · JavascriptMick/nuxt3-boilerpl...
Simple boilerplate for SAAS. Nuxt3, Supabase, OAuth, Prisma, TRPC, Pinia, Stripe, Tailwind, OpenAI - nuxt3-boilerplate/trpc.ts at master · JavascriptMick/nuxt3-boilerplate