Back to Examples

API Error Model + Client Handling Pattern

A battle-tested, consistent error shape + TypeScript client handling code.

Skill DefinitionsIntermediatetypescript
Example Code
// Shared error model (use this everywhere)
export class ApiError extends Error {
  constructor(
    public code: string,           // MACHINE_READABLE e.g. "VALIDATION_ERROR"
    message: string,               // Human friendly
    public details?: Record<string, unknown>,
    public requestId?: string,
  ) {
    super(message);
    this.name = 'ApiError';
  }
}

// Client helper
export async function handleApiResponse<T>(res: Response): Promise<T> {
  if (res.ok) return res.json();
  const err = await res.json().catch(() => ({}));
  throw new ApiError(err.code || 'UNKNOWN', err.message || res.statusText, err.details, err.requestId);
}

When to use this

A battle-tested, consistent error shape + TypeScript client handling code.