Handling tRPC Errors Gracefully
Implement best practices for catching and responding to errors within tRPC procedures and middleware.
API Errors: A Necessary Evil
In any robust API, errors are inevitable. Users might send invalid data, resources might not exist, or external services could fail.
Implementing graceful error handling is crucial for creating stable and user-friendly applications. It allows your API to respond predictably and informatively.
How tRPC Handles Errors
By default, tRPC automatically catches any JavaScript errors thrown within your procedures or middleware. It serializes them and sends them to the client.
Generic errors are often mapped to an INTERNAL_SERVER_ERROR (HTTP 500) status on the client side if not explicitly handled. Try running this example to see a generic error.
function fetchData(shouldFail: boolean) {
if (shouldFail) {
throw new Error("Something went wrong on the server!");
}
return "Data fetched successfully.";
}
function main() {
try {
console.log("Attempting to fetch (success):");
console.log(fetchData(false));
} catch (error: any) {
// This catch block demonstrates local error handling
// tRPC server would catch and serialize if not handled here
console.log(`Caught error: ${error.message}`);
}
try {
console.log("\nAttempting to fetch (fail):");
fetchData(true);
} catch (error: any) {
console.log(`Caught error: ${error.message}`);
}
}
main();All lessons in this course
- Handling tRPC Errors Gracefully
- Custom Error Types
- Data Transformers for Serialization
- Formatting Errors and Field-Level Validation Feedback