• #Error Handling

    A guide on how to handle errors. Frontend-flavoured, but most of it applies anywhere, including Python on the backend. The only truly frontend-specific bits are React error boundaries and the toast/banner patterns. Those are called out where they appear.

    The whole thing boils down to: make errors specific, keep them as values, translate them at layer boundaries, handle them as late as possible.


    1. Make specific errors

    Don't throw new Error("something went wrong"). Extend your own error class so the type itself carries meaning, and so you can act on it.

    Errors should be specific enough that the handler can do something useful with them, and they should carry the relevant info as fields.

    class UserNotFoundError extends DomainError {
      readonly kind = "user-not-found" as const;
      constructor(public readonly userId: string, cause?: unknown) {
        super(`User ${userId} not found`, { cause });
      }
    }
    
    class UserNotFoundError(DomainError):
        kind = "user-not-found"
        def __init__(self, user_id: str, cause: Exception | None = None):
            super().__init__(f"User {user_id} not found")
            self.user_id = user_id
            self.__cause__ = cause
    

    The kind (or _tag, whatever you like) field makes these usable as a discriminated union, so the handler can switch on it and the type system helps you stay exhaustive.

    Use cause to capture the underlying error

    Error.cause is standard ES2022. Python has raise ... from ... (or __cause__ directly) for the same purpose. Use it whenever you wrap or translate an error so the original is preserved in the chain. Sentry walks the chain automatically, so you get a full trace without doing anything extra.

    try {
      return await db.query(/* ... */);
    } catch (e) {
      throw new UserRepositoryError("failed to load user", { cause: e });
    }
    
    try:
        return db.query(...)
    except DatabaseError as e:
        raise UserRepositoryError("failed to load user") from e
    

    This ties directly into layer ownership: the cause is how the lower-layer error survives translation without leaking.


    2. Each layer owns its errors

    No layer should simply pass errors on. Errors are implementation details and shouldn't leak across boundaries.

    The point is not that every layer needs its own bespoke wrapper class for every case. It's that the information shouldn't get lost and should still be usable in a switch. How that's achieved depends on context. Sometimes a translated error class is the right call, sometimes a tagged union of errors generated from the OpenAPI schema is enough on its own. As long as the consumer can discriminate the cases without reaching into a lower layer's types, the goal is met.

    Concrete cases:

    • A backend should never expose an SQL error to the client. Cleanliness, but also security: SQL errors leak schema.
    • An API adapter on the frontend shouldn't let raw fetch rejections or HTTP status codes bubble into business logic. The shape of the error is up to you, what matters is that the upstream consumer doesn't have to know about Response.
    • A repository shouldn't let ORM errors reach the use case.

    When a translation does happen, it uses cause so debugging is still possible.

    async function getUser(id: string): Promise<Result<User, GetUserError>> {
      const res = await fetch(`/api/users/${id}`);
      if (res.status === 404) return err(new UserNotFoundError(id));
      if (!res.ok) return err(new ApiError(res.status, { cause: await res.text() }));
      return ok(await res.json());
    }
    

    3. Have an UnknownError

    We will forget to handle something. An explicit UnknownError (or UnexpectedError) for the "we messed up" case is much better than letting raw Error instances escape.

    It serves two purposes:

    • Makes the catch-all in your union explicit, so exhaustive matching (switch plus assertNever) actually works.
    • Gives the generic handler (§7) something predictable to render.
    function assertNever(x: never): never {
      throw new UnknownError("non-exhaustive match", { cause: x });
    }
    

    This is the safety net at the type level. Error boundaries are the safety net at runtime.


    4. Domain errors live in the business layer

    If a layer has complex logic and many failure cases, it gets its own errors. These tend to be the most valuable ones because they encode actual business invariants:

    • InsufficientFundsError
    • OrderAlreadyShippedError
    • EmailAlreadyTakenError

    These map naturally to UI affordances (§7). EmailAlreadyTakenError becomes a field error on the email input, no string-matching required.


    5. Don't throw, return Results

    Throwing is invisible to the type system (TS has no checked exceptions, Python has none at all). Returning a Result<T, E> makes the error part of the signature, and the caller can't accidentally ignore it.

    type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
    
    type GetUserError = UserNotFoundError | ApiError | UnknownError;
    function getUser(id: string): Promise<Result<User, GetUserError>> { /* ... */ }
    

    Roll your own (it's twenty lines) or pick a library if you want the ergonomics. The pattern works the same on the backend: a Result type or a tagged union return value beats raising for expected failure cases.

    Throw only where an adapter requires it. React renders, framework lifecycle hooks, event handlers wired to libraries that expect throws, FastAPI/Flask exception handlers that translate to HTTP responses. Those are the boundary. Your own code returns Results. The throw at the boundary then gets caught and turned back into a value (or a response).


    6. Handle errors where you can, not earlier

    An error should travel up until it reaches a layer that can actually do something useful with it. Earlier handling either swallows information or forces lower layers to know about UI concerns.

    Example flow for a failed API call:

    1. API adapter sees a 503. It knows this is transient, retries with backoff. Succeeds, done. Fails again, returns err(new ApiUnavailableError(...)).
    2. Use case / query layer has nothing useful to do with ApiUnavailableError. Passes it up unchanged (still as a Result).
    3. UI receives the error. Shows it to the user, logs it, reports it to Sentry.

    The rule of thumb: don't catch unless you're adding value, meaning translating the error, retrying, or actually resolving it. A catch that just re-throws is noise, and worse, often loses the stack.

    Logging follows the same principle. Log at the point of handling, not at every layer the error passes through, otherwise Sentry fills up with multiple copies of the same incident.


    7. Three ways to handle an error

    Once an error reaches a place that can act on it, there are three flavours of handling. They compose; one error can trigger all three.

    Recover (acting)

    The handler does something programmatic. The user may not even see this happen.

    • 401 redirects to login
    • Token expired, refresh and retry
    • Stale cache, invalidate and refetch

    Surface (presenting)

    A specific piece of UI shows context-appropriate feedback. This is where domain errors pay off, because they map to UI states without string-matching.

    • EmailAlreadyTakenError becomes a field error on the email input
    • InsufficientFundsError becomes an inline warning next to the amount
    • OrderAlreadyShippedError disables the cancel button and explains why

    Fallback (generic)

    Always present, because we will never anticipate every error. Start here. Wire up the generic handler before the specific ones, so unhandled errors fail loudly but gracefully.

    The shape depends on what triggered the error:

    • Actions / mutations (user-initiated, transient): error toast. The user did a thing, the thing failed, they want to know and try again. Maps to TanStack Query's mutation.onError.
    • Queries (data-shaped, persistent): inline banner or block element where the data should have been. The screen is broken, not an action. Maps to TanStack Query's query.error rendered inside the component.

    The fallback is also where reporting happens: Sentry call, user-friendly message, optionally a "copy error id" affordance.


    8. Error boundaries

    This is the bulkhead pattern from resilience engineering. A ship is divided into watertight compartments so a breach floods one section, not the whole vessel. Applied to software: an isolation barrier around a region contains a failure to that region, leaving the rest running in a degraded state.

    The pattern is general. A failing widget shouldn't take down the page. A failing background job shouldn't take down the worker. A failing downstream service shouldn't take down the API (circuit breakers are the network-layer version of the same idea).

    In React

    React's ErrorBoundary is the implementation of this pattern for the render tree. It catches errors thrown during render (and in lifecycle methods) and renders a fallback UI instead of letting the whole tree unmount. It does not catch:

    • errors in event handlers
    • errors in async code
    • errors in useEffect callbacks

    That's fine. Those are the cases where §5 applies and you should be returning Results anyway. The boundary is the safety net for "something escaped our model", which ties back to §3.

    Stack them

    One at the page root catches catastrophes. More granular ones around independent regions (sidebar, widget, panel) keep the rest of the page running when one piece breaks.

    <RootBoundary>
      <Header />
      <SidebarBoundary><Sidebar /></SidebarBoundary>
      <MainBoundary>
        <WidgetBoundary><Widget /></WidgetBoundary>
        <WidgetBoundary><Widget /></WidgetBoundary>
      </MainBoundary>
    </RootBoundary>
    

    Always wrap with a named error

    When the boundary catches something, don't log the raw error. Wrap it in a named one with the original as cause. This is what makes the report useful later when you're trying to figure out where it came from.

    class RenderError extends AppError {
      readonly kind = "render-error" as const;
      constructor(public boundary: string, cause: unknown) {
        super(`render failed in ${boundary}`, { cause });
      }
    }
    

    Pair it with logging that includes the boundary name and the component tree. Now Sentry tells you both what went wrong (the cause) and where it was contained (the boundary).


    TL;DR

    • Specific error classes, with cause chains.
    • Translate at layer boundaries; the form depends on context, the goal is that information doesn't get lost and stays usable in a switch.
    • Have an UnknownError for the gaps.
    • Domain errors encode business invariants and map cleanly to UI.
    • Return Results in your own code; throw only where adapters demand it.
    • Handle as late as possible, where the handler can actually do something.
    • Three handling modes: recover, surface, fallback. Always have a fallback.
    • Stack error boundaries (bulkheads) for runtime isolation; wrap caught errors in named ones.