Error Handling and Typed Errors
What you'll learn: How to create custom error types that are automatically inferred on the client side for fully type-safe error handling in tRPC procedures.
The Problem with Untyped Errors
In standard API frameworks, when something goes wrong, you throw an error or return an error response. But on the client side, you often have no idea what kind of error might come back. You end up writing defensive code that checks string properties or status codes, with no autocomplete and no compile-time guarantees.
tRPC's beauty is that types flow from server to client. But what about when things fail?
Custom Error Classes with Type Inference
In tRPC, you can define custom error classes that extend the framework's base error type. When you throw these errors in your procedures, tRPC automatically makes them available on the client with full type information.
class ValidationError extends TRPCError {
constructor(public field: string, message: string) {
super({ code: 'BAD_REQUEST', message });
}
}
class NotFoundError extends TRPCError {
constructor(public resourceId: string) {
super({ code: 'NOT_FOUND', message: 'Resource not found' });
}
}
When your procedure throws ValidationError, the client-side error object knows it has a field property. When it throws NotFoundError, the client knows about resourceId. This is type-safe error handling: your catch blocks have autocomplete for error-specific properties.
Type-Safe Error Discrimination
Because these are distinct types, you can use discriminated union patterns (based on error codes or error shapes) to narrow which error you're handling. The client can check the error code and TypeScript will narrow the type, giving you access to the specific properties of that error class.
Key Takeaway: tRPC's typed errors let you define custom error classes on the server that are automatically inferred on the client, enabling compile-time safety and autocomplete when handling different failure cases—bringing the same type safety to your error paths that you have for success paths.