0PricingLogin
tRPC End-to-End Type Safe APIs · Lesson

Custom Error Types

Define and throw custom error types from your backend that are correctly propagated to the frontend.

Why Custom Error Types?

In tRPC, we often use TRPCError for handling issues. But sometimes, you need more specific error types.

  • Clarity: Custom errors make your code clearer about what went wrong.
  • Specific Handling: Allows the frontend to react differently to distinct error conditions.
  • Better Debugging: Provides more context than a generic error.

Let's learn how to define and use them!

Basic Custom Error Class

At its simplest, a custom error is a class that extends JavaScript's built-in Error class. This ensures it behaves like a standard error.

It usually takes a message and sets its own name property.

class MyCustomError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'MyCustomError';
  }
}

function main() {
  try {
    throw new MyCustomError('Something specific went wrong!');
  } catch (error) {
    if (error instanceof MyCustomError) {
      console.log(`Caught: ${error.name} - ${error.message}`);
    } else {
      console.log(`Caught generic error: ${error.message}`);
    }
  }
}

main();

All lessons in this course

  1. Handling tRPC Errors Gracefully
  2. Custom Error Types
  3. Data Transformers for Serialization
  4. Formatting Errors and Field-Level Validation Feedback
← Back to tRPC End-to-End Type Safe APIs