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

Skip to content

ExamplesError Handling

Error Handling

HTTPError class, isHTTPError type guard, and global error callbacks.

HTTPError — Catch & Inspect

HTTPError provides status, data, and headers. Select an error code and trigger it: the request below shows which leg answered with the error — here the API, its answer passed on by the route. This site's server names each call in X-Courier-Rid, so the id error.headers holds is the one the request shows.

run the call
ts
import { HTTPError } from "@noverax/courier/client"
import { caller } from "@/lib/caller"

try {
  await caller.misc.error({ code: 404 })
} catch (error) {
  if (error instanceof HTTPError) {
    console.log(error.status)  // 404
    console.log(error.data)    // { success: false, message: "..." }
    console.log(error.headers) // Headers: the answer's own
  }
}
caller.misc.error({ code })SANDBOX
idle
// run the request to see the response

Requests

as the browser recorded them and the site's server told of them

// no request yet: run the call

Error handling docs

isHTTPError — Type Guard

Use isHTTPError() to narrow unknown errors. TypeScript infers status, data, and headers.

ts
import { isHTTPError } from "@noverax/courier/client"
import { caller } from "@/lib/caller"

try {
  await caller.misc.error({ code: 403 })
} catch (error) {
  if (isHTTPError(error)) {
    // TypeScript knows: error.status, error.data, error.headers
    handleHttpError(error)
  } else {
    // Network error, timeout, etc.
    handleUnknownError(error)
  }
}
isHTTPError(error)SANDBOX
idle
// run the request to see the response

Requests

as the browser recorded them and the site's server told of them

// no request yet: run the call

Global onError / onSuccess

Configure global callbacks for all requests in createProxyCaller defaults.

ts
import { createProxyCaller, isHTTPError } from "@noverax/courier/client"
import { routes } from "@noverax/courier/routes"

const caller = createProxyCaller(routes.api, {
  // Called for every failed request: an HTTP error, a network failure or a timeout
  onError: (error) => {
    toast.error(`Request failed: ${error.message}`)

    if (isHTTPError(error) && error.status === 401) {
      router.push("/login")
    }
  },

  // Called for every successful request
  onSuccess: (data) => {
    console.log("Success:", data)
  },
})

Global callbacks fire for every request. Useful for toast notifications, auth redirects, and logging.