Customizing Error Codes in TypeScript React with tRPC

This blog post guides you through customizing error codes in tRPC for TypeScript React applications, enhancing error handling.

Blog cover image
2101050's avatar
2101050
29 views

Customizing Error Codes in TypeScript React with tRPC

In modern web development, handling errors gracefully is crucial for providing a seamless user experience. When using tRPC in a TypeScript React application, you have the flexibility to customize error codes to better suit your application's needs. This blog post will guide you through the process of customizing error codes in tRPC, highlighting key points and providing practical examples.

Introduction to tRPC Error Handling

tRPC is a powerful tool for building type-safe APIs in TypeScript. It provides a built-in error handling mechanism through the TRPCError class, which allows you to define and manage errors effectively. However, there are scenarios where you might need to define custom error codes to handle specific business logic or application requirements.

Key Points for Customizing Error Codes

1. Using tRPC's Built-in Error Handling

tRPC's TRPCError class allows you to specify error codes and messages. This is the simplest way to handle errors:

Typescript
1import { TRPCError } from '@trpc/server'; 2 3const appRouter = router({ 4 getUser: publicProcedure 5 .input(z.string()) 6 .query(async ({ input }) => { 7 const user = await db.user.findUnique({ where: { id: input } }); 8 if (!user) { 9 throw new TRPCError({ 10 code: 'NOT_FOUND', 11 message: 'User not found', 12 cause: 'USER_NOT_FOUND_IN_DB', 13 }); 14 } 15 return user; 16 }), 17}); 18

2. Extending tRPC Error Code Types

For more control, you can extend the error code types in tRPC to include custom codes:

Typescript
1// src/server/trpc.ts 2import { initTRPC, TRPCError } from '@trpc/server'; 3 4const t = initTRPC.create(); 5 6type CustomErrorCode = 'USER_NOT_FOUND' | 'INVALID_PERMISSION' | 'CUSTOM_ERROR'; 7 8declare module '@trpc/server' { 9 interface TRPCErrorCode extends CustomErrorCode {} 10} 11 12export const router = t.router; 13export const publicProcedure = t.procedure; 14

3. Creating Custom Error Classes

For complex scenarios, creating a custom error class can be beneficial:

Typescript
1import { TRPCError } from '@trpc/server'; 2 3export class CustomTRPCError extends TRPCError { 4 constructor( 5 public customCode: string, 6 message: string, 7 opts?: { cause?: unknown } 8 ) { 9 super({ 10 code: 'INTERNAL_SERVER_ERROR', 11 message, 12 cause: opts?.cause, 13 }); 14 } 15} 16 17// Usage 18throw new CustomTRPCError('MY_CUSTOM_CODE', 'Something went wrong'); 19

4. Handling Errors on the Client Side

In your React components, you can handle these custom errors effectively:

Typescript
1import { trpc } from '../utils/trpc'; 2 3function UserProfile({ userId }: { userId: string }) { 4 const { data, error } = trpc.getUser.useQuery(userId); 5 6 if (error) { 7 if (error.data?.code === 'NOT_FOUND') { 8 return <div>User not found</div>; 9 } 10 if (error.data?.code === 'USER_NOT_FOUND') { 11 return <div>Custom error handling</div>; 12 } 13 return <div>Error: {error.message}</div>; 14 } 15 16 return <div>{data?.name}</div>; 17} 18

5. Global Error Handling

You can set up a global error formatter to standardize error responses:

Typescript
1// src/server/trpc.ts 2import { initTRPC } from '@trpc/server'; 3 4const t = initTRPC.create({ 5 errorFormatter({ shape, error }) { 6 return { 7 ...shape, 8 data: { 9 ...shape.data, 10 customCode: error.cause instanceof CustomTRPCError ? error.cause.customCode : undefined, 11 }, 12 }; 13 }, 14}); 15

Best Practices

  • Define Clear Error Codes: Create an enumeration of error codes that are meaningful and easy to understand.
  • Document Error Codes: Maintain documentation for all possible error codes to aid in debugging and development.
  • Use HTTP Status Codes: Consider aligning your custom error codes with HTTP status codes for consistency.
  • Centralize Error Handling: Use utility functions to handle common errors across your application.

Conclusion

Customizing error codes in tRPC allows you to handle errors in a way that aligns with your application's specific needs. By extending error types, creating custom error classes, and implementing global error handling, you can ensure a robust and user-friendly error management system. With these strategies, you can enhance the reliability and maintainability of your TypeScript React applications.

Recommended Articles

Discover more articles you might find interesting

Implementing LangGraph REST API with FastAPI
Technical Insights

Implementing LangGraph REST API with FastAPI

This guide provides a comprehensive implementation plan for building a LangGraph REST API using FastAPI, covering environment setup, agent definitions, endpoint creation, testing, and deployment.

2101050
Jun 18
153
Read More
DeepSite v2 Practical Guide
Technical Insights

DeepSite v2 Practical Guide

A comprehensive guide to DeepSite v2, covering its features, installation, and advanced workflows.

2101050
Jun 21
112
Read More
Fastify OpenTelemetry: Logging, Metrics, and Tracing in Practice
Technical Insights

Fastify OpenTelemetry: Logging, Metrics, and Tracing in Practice

Learn how to implement logging, metrics, and tracing in Fastify using OpenTelemetry.

2101050
Jul 11
106
Read More
Creating Diverse Logo Designs with Flux Model and ComfyUI
Technical Insights

Creating Diverse Logo Designs with Flux Model and ComfyUI

Learn to leverage the Flux model and ComfyUI for unique logo designs through effective prompts and examples.

2101050
Jan 10
93
Read More
Formatting Dates in TypeScript to UTC
Technical Insights

Formatting Dates in TypeScript to UTC

A guide on how to format dates in TypeScript to the specific format YYYY-MM-DDTHH:mm:ss+00:00.

2101050
Dec 19
83
Read More
Implementing a Custom Chat Model with LangChain
Technical Insights

Implementing a Custom Chat Model with LangChain

This guide provides a comprehensive blueprint for creating a custom chat model by subclassing LangChain's BaseChatModel, including configuration, method overrides, and error handling.

2101050
Jun 17
78
Read More