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();