Error Handling

If a procedure fails we trigger a function with information about the procedure & ctx.

Example with Next.js#

export default trpcNext.createNextApiHandler({
// [...]
onError({ error }) {
console.error('Error:', error);
if (error.code === 'INTERNAL_SERVER_ERROR') {
// send to bug reporting
}
},
});

All properties sent to onError()#

{
error: TRPCError;
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined; // path of the procedure that was triggered
input: unknown;
ctx: Context | undefined;
req: BaseRequest; // request object
}

Built-in error codes#

CodeHTTP StatusDescription
BAD_USER_INPUT400 / 413Input validation failed. 413 if data exceeds maxBodySize
NOT_FOUND404Procedure path not found
UNAUTHENTICATED401Unauthorized request
FORBIDDEN403Forbidden request
INTERNAL_SERVER_ERROR500Something in the resolver threw an error
TIMEOUT408Used in subscriptions to tell client to reconnect

Accessing original error#

export default trpcNext.createNextApiHandler({
// [...]
onError({ error }) {
console.error('Error:', error);
console.log('Original error thrown', error.originalError);
},
});

Error helpers#

import * as trpc from '@trpc/server';
// in your resolver:
throw trpc.httpError.unauthorized('Optional message') // --> 401
throw trpc.httpError.forbidden('Optional message') // --> 403
throw trpc.httpError.badRequest('Optional message') // --> 400
throw trpc.httpError.notFound('Optional message') // --> 404