This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

Core ConceptsError Handling

Error Handling

Tell an error answer, a request that got no answer and one that ran out of time apart, with typed error data, type guards, and middleware-based error hooks.

5 min readUpdated both modes

What a Failed Call Rejects With

A call that got no successful answer rejects with one of three errors, told apart by what happened rather than by a status:

ErrorWhenWhat it carries
HTTPErrorThe upstream answered with an error status, 400 or abovestatus, headers, the parsed data
NetworkErrorNo answer came: a host that does not resolve, a connection refused or dropped, a certificate refusedsystemCode — ECONNREFUSED, ENOTFOUND, … where the platform gave one — and the platform's error as cause
TimeoutErrorThe time ran out: the request's timeout, or a retry policy's deadlinescope — "attempt" or "deadline" — and timeout in ms

Each extends Courier's CourierError, itself an Error, with a stable code: "HTTP_ERROR", "NETWORK_ERROR" or "TIMEOUT". isRequestFailure() is true for all three, and the type RequestFailure names them together — what a caller's onError receives. See NetworkError, TimeoutError & AbortError.

A call that was cancelled rejects with an AbortError instead, which is no failure: code "ABORTED" when its signal aborted, the reason it was given as cause, and "SUPERSEDED" when a newer call of its endpoint took its place. isAbortError() tells it apart; onError is not told of it.

The HTTPError Class

When a request gets an answer with an HTTP error status (400 or above), Courier throws an HTTPError. It adds status, headers, and a typed data property containing the parsed response body:

typescript
import { CourierError } from "@noverax/courier/client"

declare class HTTPError<TData = unknown> extends CourierError<"HTTP_ERROR"> {
  readonly status: number    // The answer's HTTP status code (400, 404, 500, ...): always 100 to 599
  readonly headers: Headers  // Response headers
  readonly data: TData       // Parsed response body — typed with the TData generic
}

// error.message → "HTTP 404"
// error.name → "HTTPError"

Typed error data

The HTTPError<TData> generic lets you type the error response body. If your backend returns { "message": "Not found", "code": "NOT_FOUND" }, you can access it as error.data.message with full type safety.

The isHTTPError Type Guard

Use isHTTPError() to narrow an unknown error to HTTPError. It works as a TypeScript type guard, giving you access to status, headers, and data inside the if block:

lib/api-helpers.ts
import { isHTTPError } from "@noverax/courier/client"

try {
  const user = await caller.users.getById({ id: "999" })
} catch (error) {
  // Type guard narrows error to HTTPError
  if (isHTTPError(error)) {
    console.log(error.status)  // 404
    console.log(error.data)    // whatever the backend returned
  }

  // With a typed error body
  if (isHTTPError<{ message: string; code: string }>(error)) {
    console.log(error.data.message) // "User not found"
    console.log(error.data.code)    // "USER_NOT_FOUND"
  }
}

Error Handling Patterns

Direct mode — try/catch

In Server Components and Server Actions, use standard try/catch to handle errors from createCaller:

app/users/[id]/page.tsx
import { isHTTPError } from "@noverax/courier/server"
import { caller } from "@/lib/caller"

export default async function UserPage({ params }: { params: { id: string } }) {
  try {
    const user = await caller.users.getById({ id: params.id })

    return <UserProfile user={user} />
  } catch (error) {
    if (isHTTPError(error)) {
      if (error.status === 404) {
        return <NotFound message="User not found" />
      }
      return <ErrorPage status={error.status} />
    }
    throw error // Re-throw unexpected errors for error boundary
  }
}

Without try/catch

A method's .safe() resolves to { data, error } instead of rejecting: the data and no error, or no data and why the call failed. A cancelled call still rejects — see Calling Without Throwing.

typescript
async function showUser(id: string) {
  const { data, error } = await caller.users.getById.safe({ id })
  if (error) return report(error.code)
  render(data)
}

Proxy mode — React Query

When using createProxyQueryCaller, React Query catches errors automatically and exposes them via the error property:

components/users.tsx
"use client"

import { isHTTPError } from "@noverax/courier/client"
import { q } from "@/lib/query"

export function UsersList() {
  const { data, error, isError } = q.users.useQuery("getAll")

  // React Query catches errors automatically
  if (isError && isHTTPError(error)) {
    return <div>Error {error.status}: Failed to load users</div>
  }

  return <ul>{data?.map((u) => <li key={u.id}>{u.name}</li>)}</ul>
}

export function CreateUserForm() {
  const { mutate, error, isError } = q.users.useMutation("create", {
    onError: (error) => {
      // Handle error in the mutation callback
      if (isHTTPError<{ message: string }>(error)) {
        toast.error(error.data.message)
      }
    },
  })

  return (
    <form onSubmit={(e) => {
      e.preventDefault()
      mutate({ name: "Jane", email: "jane@test.com" })
    }}>
      {isError && isHTTPError(error) && (
        <p className="text-red-500">Error: {error.status}</p>
      )}
      <button type="submit">Create User</button>
    </form>
  )
}

Middleware-Based Error Handling

For cross-cutting error handling (logging, authentication redirects, toast notifications), define a custom middleware with defineMiddleware. This middleware wraps every request in the source and can intercept errors before they reach your components:

api/sources.ts
import { defineApi } from "@noverax/courier/define"
import { defineMiddleware } from "@noverax/courier/middleware"
import { isHTTPError } from "@noverax/courier/client"
import { users } from "./users"
import { posts } from "./posts"

const errorMiddleware = defineMiddleware("errors", "wrap", async (ctx, next) => {
  try {
    return await next()
  } catch (error) {
    // Log to your error tracking service
    if (isHTTPError(error)) {
      console.error(
        `[${ctx.source}] ${ctx.group}:${ctx.method} failed with ${error.status}`,
        { variables: ctx.variables, data: error.data },
      )

      // Handle 401 globally — redirect to login, refresh token, etc.
      if (error.status === 401) {
        window.location.href = "/login"
      }
    }

    // Re-throw so try/catch and React Query still receive the error
    throw error
  }
})

const api = defineApi({
  baseURL: process.env.API_URL!,
  middleware: [errorMiddleware],
  groups: { users, posts },
})

export const sources = { api }

Middleware does not suppress errors

The middleware re-throws the error after handling side effects. Your try/catch or React Query error handling will still receive it. If you want to suppress an error, return a fallback MiddlewareResponse instead of re-throwing.

Combining with Built-in Middleware

You can compose the error middleware with Courier's built-in middleware. Middleware executes in array order — the first middleware is the outermost wrapper:

api/sources.ts
import { defineApi } from "@noverax/courier/define"
import {
  defineMiddleware,
  retryMiddleware,
  logMiddleware,
  authMiddleware,
} from "@noverax/courier/middleware"

const api = defineApi({
  baseURL: process.env.API_URL!,
  middleware: [
    logMiddleware(),                                   // logs endpoint, status, duration
    retryMiddleware({ limit: 2, delay: 300 }),         // retries a dropped request, 429, 5xx
    authMiddleware({ getToken: () => getAuthToken() }),  // attaches Bearer token
    errorMiddleware,                                   // custom error handling
  ],
  groups: { users, posts },
})

Error Types

Courier can throw different types of errors depending on the failure mode:

typescript
// 1. HTTP errors (status >= 400) — most common
// The backend returned an error response with a body
if (isHTTPError(error)) {
  error.status   // 400, 401, 403, 404, 500, ...
  error.data     // Parsed response body (JSON or text)
  error.headers  // Response headers
}

// 2. Network errors — no response received
// Thrown as NetworkError, message "Network request failed (ECONNREFUSED)";
// error.systemCode carries the system's code (ECONNREFUSED, ENOTFOUND, ...)
// where it gave one, and error.cause the error fetch rejected with.
if (isNetworkError(error)) {
  error.systemCode // "ECONNREFUSED", or undefined in a browser
}

// 3. Timeouts — the request's timeout, or a retry policy's deadline, ran out
// Thrown as TimeoutError, message "Request timed out after 5000 ms".
// Through the proxy, a timeout on the server's side of the call arrives
// as HTTPError 504 with error.data.code "UPSTREAM_TIMEOUT"; a host the
// server could not reach arrives as 502 with "UPSTREAM_UNREACHABLE".
if (isTimeoutError(error)) {
  error.scope   // "attempt" or "deadline"
  error.timeout // 5000
}

// 4. Cancellation
// A call cancelled through your own signal rejects with an AbortError,
// code "ABORTED", the reason you gave as its cause — the platform's
// DOMException when you gave none. This holds while the answer's body is
// still being read, too. A read a newer call of its endpoint superseded —
// cancelPrevious on for both — rejects with code "SUPERSEDED".
if (isAbortError(error)) {
  error.code  // "ABORTED", or "SUPERSEDED" when a newer read of the same endpoint took its place
  error.cause // the reason the signal was given
}

// 5. Your own code's failures
// On a direct call, what a middleware or a pathOptions function threw,
// or a body that would not serialize, is rethrown as it was.

// 6. JSON parse errors — a success whose body is not valid JSON
// Thrown when responseType is "json" but a 2xx body cannot be parsed:
// an HTTPError carrying the upstream's own status (e.g. 200), with the
// SyntaxError as its cause. Through the proxy it arrives as a 502.
// An error answer whose body is not JSON is not a parse error: its
// text becomes error.data.

Next Steps

  • HTTP Client & Methods — how requests are executed under the hood
  • Type Safety — how types flow from definitions to error handling
  • Middleware — built-in retry, auth, logging, rate limiting, and caching middleware