T
tRPC

❓-help

TRPC & Zod Logging

Jjoseph12/31/2023
I'm building a backend and if my input validation fails I want to log the failure but couldn't figure out a way as trpc seems to handle the error straigth away, anyone know how this could be done?
AEAhmed Elsakaan12/31/2023
I think you can do that in the errorFormatter method on the initTRPC.create function call, like so:
const t = initTRPC.context<Context>().create({
transformer: SuperJSON,
errorFormatter(opts) {
const { shape, error } = opts;

// log error
console.log(error);

return {
...shape,
data: {
...shape.data,
zodError:
error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
? error.cause.flatten()
: null,
},
};
},
});
const t = initTRPC.context<Context>().create({
transformer: SuperJSON,
errorFormatter(opts) {
const { shape, error } = opts;

// log error
console.log(error);

return {
...shape,
data: {
...shape.data,
zodError:
error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
? error.cause.flatten()
: null,
},
};
},
});
Jjoseph12/31/2023
Yep i saw this, but what if i want to log a specific error to my db e.g. 'validation failed on login'

Looking for more? Join the community!