Handling API Error Types End-to-End
What you'll learn: How to define typed error responses on the backend and ensure your frontend code handles all possible error cases safely.
The Problem: Error Responses Are Data Too
When we talk about type-safe APIs, we often focus on success cases—typed request bodies, typed responses. But errors are just as much part of your API contract. Without typed errors, your frontend might handle a 404 differently than a 500, or forget to check for validation errors entirely.
Think of it like a restaurant menu that only lists the meals, not the allergen warnings. Your API types should document both the happy path and what can go wrong.
Defining Backend Error Types
First, create a discriminated union for your API errors:
type ApiError =
| { type: 'validation'; field: string; message: string }
| { type: 'notFound'; resource: string }
| { type: 'unauthorized'; reason: string }
| { type: 'serverError'; message: string };
type ApiResponse<T> =
| { success: true; data: T }
| { success: false; error: ApiError };
The type discriminant lets the frontend exhaustively check all error cases.
Frontend Error Handling
With shared types, your frontend can handle every case safely:
async function getUser(id: string): Promise<User> {
const response = await fetch(`/api/users/${id}`);
const result: ApiResponse<User> = await response.json();
if (!result.success) {
switch (result.error.type) {
case 'validation':
throw new Error(`Invalid ${result.error.field}: ${result.error.message}`);
case 'notFound':
throw new Error(`User not found`);
case 'unauthorized':
throw new Error(`Unauthorized: ${result.error.reason}`);
case 'serverError':
throw new Error(result.error.message);
// TypeScript ensures we've handled all cases
}
}
return result.data;
}
The compiler prevents you from forgetting an error type—if you add a new error variant, every switch statement becomes incomplete until you handle it.
Key Takeaway: Type your error responses as discriminated unions and share them across your stack—this turns runtime error handling from guesswork into an exhaustive, compiler-verified checklist.