Error Handling

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

Example with Next.js

  1. export default trpcNext.createNextApiHandler({
  2. // [...]
  3. onError({ error }) {
  4. console.error('Error:', error);
  5. if (error.code === 'INTERNAL_SERVER_ERROR') {
  6. // send to bug reporting
  7. }
  8. },
  9. });

All properties sent to onError()

  1. {
  2. error: TRPCError;
  3. type: 'query' | 'mutation' | 'subscription' | 'unknown';
  4. path: string | undefined; // path of the procedure that was triggered
  5. input: unknown;
  6. ctx: Context | undefined;
  7. req: BaseRequest; // request object
  8. }

Accessing original error

  1. export default trpcNext.createNextApiHandler({
  2. // [...]
  3. onError({ error }) {
  4. console.error('Error:', error);
  5. console.log('Original error thrown', error.cause);
  6. },
  7. });

Error helpers

  1. import { TRPCError } from '@trpc/server';
  2. throw new TRPCError({
  3. code: 'INTERNAL_SERVER_ERROR',
  4. message: 'Optional Message',
  5. // optional: pass your thrown error to TRPCError to retain stack trace
  6. cause: myError,
  7. });
  8. // Some available codes:
  9. //
  10. // "FORBIDDEN"
  11. // "BAD_REQUEST"
  12. // "INTERNAL_SERVER_ERROR"
  13. // "NOT_FOUND"
  14. // "TIMEOUT"
  15. // "PRECONDITION_FAILED"