Typed Error Handling with Orval and FastAPI

· min read

In the setup post, we used Orval to turn FastAPI’s OpenAPI spec into a typed function for every route. As long as a call succeeds, TypeScript knows exactly what comes back.

When a call fails, we lose that. The error lands in a catch block with no type, so the frontend has to guess what the backend sent and where the message is. That’s the kind of guessing the generated client was supposed to end.

The fix is to describe errors in the spec too: one error shape for every failed request, which Orval then types like everything else. FastReact is built this way, along with many other best practices for a FastAPI and React app, so the examples below come from its code.

Return every error in the same shape

Orval only types what the spec describes, and by default FastAPI’s spec describes successful responses plus a 422 for validation. The errors don’t even share a shape. HTTPException sends {"detail": "Not found"}, a validation error sends {"detail": [...]} with a list of field problems, and an unhandled crash sends the plain text Internal Server Error. So the frontend ends up writing this:

catch (e: any) {
	alert(e?.detail ?? e?.message ?? 'Something went wrong');
}

Let’s start with the backend. Every exception handler returns the same body, defined by one Pydantic model:

# backend/app/model/error_model.py
class ErrorResponse(BaseModel):
    code: str
    message: str
    error_id: str | None = None
    details: dict | None = None
  • code is for the frontend to branch on, like NOT_FOUND or VALIDATION_ERROR.
  • message is written for the user.
  • error_id is also written to the server log, so when a user sends us a screenshot of the error, we can find the exact request.
  • details carries extra data when an error needs it, like which fields failed validation.

The handlers now all return ErrorResponse, but the OpenAPI spec doesn’t know that. It still describes each route’s success response and nothing about our errors, so Orval has nothing to build an error type from. We configure this once, when we create the app. FastAPI’s responses argument adds extra responses to every route in the spec, so we use it to declare ErrorResponse for every error status, 400 through 599:

# backend/app/main.py
# Declare ErrorResponse as the body of every error status (400-599) on every route.
error_responses = {status_code: {"model": ErrorResponse} for status_code in range(400, 600)}

app = FastAPI(responses=error_responses)

When we run npm run generate again, Orval adds an ErrorResponse type to app/lib/api/gen/model.

On the frontend, every generated function sends its request through customFetch, the small fetch wrapper from the setup post (Orval’s config points to it). Since it sees every response, it’s the one place where a failed response can become a typed error:

// frontend/app/lib/api/fetch.ts (trimmed)
import type { ErrorResponse } from './gen/model';

export interface ApiError {
	response: { status: number; statusText: string; data: ErrorResponse };
}

export const customFetch = async <T>(url: string, options: RequestInit): Promise<T> => {
	// ...send the request and parse the response body into `data`...

	if (!response.ok) {
		const apiError: ApiError = {
			response: {
				status: response.status,
				statusText: response.statusText,
				data: data as ErrorResponse
			}
		};
		throw apiError;
	}

	return data as T;
};

Components catch that error and read it with two small helpers from the same file:

export function isApiError(err: unknown): err is ApiError {
	return (
		typeof err === 'object' &&
		err !== null &&
		'response' in err &&
		typeof (err as ApiError).response?.status === 'number'
	);
}

export function getErrorMessage(err: unknown, fallback: string): string {
	if (!isApiError(err)) return fallback;
	return err.response.data?.message || fallback;
}

isApiError tells us whether the request got an error response back. If the network drops, fetch throws a TypeError instead, so isApiError is false and there’s no message to show. In that case getErrorMessage returns the fallback text. It also falls back when a response does come back but isn’t one of ours, like an HTML error page from a proxy in front of the API, because that body has no message field.

Most components only need the message, so they call getErrorMessage:

// frontend/app/routes/protected/notes-edit.tsx
try {
	await updateNote(note.id, data);
} catch (err) {
	setSubmitError(getErrorMessage(err, 'Failed to update note. Please try again.'));
}

When a component has to react differently to different errors, it calls isApiError itself. Inside the if, TypeScript knows err is an ApiError, so status and code are typed and autocompleted. The login page checks both:

// frontend/app/routes/auth/login.tsx
try {
	await login({ email: data.email, password: data.password });
	setUser(await getCurrentUser());
} catch (err) {
	if (isApiError(err) && err.response.data?.code === 'EMAIL_NOT_VERIFIED') {
		navigate(`${VERIFY_EMAIL_PATH}?email=${encodeURIComponent(data.email)}`);
	} else if (isApiError(err) && err.response.status === 401) {
		setApiError('Invalid email or password.');
	} else {
		setApiError('Login failed. Please try again later.');
	}
}

A user who hasn’t verified their email is sent to the verification page instead of seeing an error. A wrong password gets a clear message. Anything else, including a network failure, falls through to the generic one. Without a shared error shape, that first check would mean parsing whatever text the backend happened to send.

Starting from a working setup

FastReact is a React SaaS boilerplate built on this setup: one ErrorResponse for every backend error, registered in the spec, a fetch wrapper with isApiError and getErrorMessage, and the Orval config and generated client already wired up. It also includes the parts this post didn’t cover: login and sessions, Stripe billing, teams and roles, and AI usage metering.

If you haven’t generated a client yet, start with How to Connect a React SPA to a FastAPI Backend.

logo-light

Ship production-ready SaaS applications with FastAPI + React. Complete authentication, payments, multi-tenancy, and admin dashboards - deploy anywhere with zero vendor lock-in.

© 2026 KeyNLP Inc. All rights reserved.

🌼 Made with daisyUI

FASTREACT