joseph
joseph10mo ago

TRPC & Zod Logging

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?
2 Replies
Ahmed Elsakaan
Ahmed Elsakaan10mo ago
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,
},
};
},
});
joseph
joseph10mo ago
Yep i saw this, but what if i want to log a specific error to my db e.g. 'validation failed on login'