Files
qqq-frontend-next/docs/API-ERROR-HANDLING.md
james.maesandClaude Fable 5.2 523f59cf38
maven / build (push) Successful in 4m33s
build / maven (push) Successful in 4m33s
fix(errors): the error banner says what failed and no longer stacks
The global query/mutation error handler showed "Something went wrong" for
every failure without an expected status, and a polling query that kept
failing added one banner per attempt.

- No response: "No response from the server" (or "The server took too long
  to respond" for a timeout), with the request below it as METHOD /path:
  no query string, and ids shown as {id}.
- Unexpected status: the server's own message, else "Request failed (HTTP 409)".
- An error raised by the application shows its own sentence; a runtime error
  shows only its type.
- The banner's sonner id is its text plus the request, so a repeat updates
  the banner on screen. A lost connection has one banner for every request.
- 401, cancelled requests and aborted fetches stay silent. 403 falls back to
  "Permission denied" instead of the axios transport text.
- Each banner logs status, axios code, error name and request to the console,
  never a message, body, header or query string.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:29:49 -06:00

13 KiB

API Error Handling Guide

This document describes how API errors flow through the QQQ Frontend Next application and what, if anything, individual components need to do about them.

The short answer is: most errors require no per-call handling. The global error handler in the query client toasts an appropriate message automatically, and the 401 interceptor in the Axios client redirects to login. Individual components only need to add their own handling when the generic behavior is insufficient for a specific UX requirement.


Architecture Overview

There are two independent error interception layers:

  1. Axios response interceptor (src/lib/api/client.ts) — fires synchronously on every HTTP response before the promise settles. Handles 401 (unauthorized) only.
  2. TanStack Query global handlers (src/lib/query-client.ts) — QueryCache.onError for reads, MutationCache.onError for writes. Fire after the interceptor. Handle all other errors by toasting a message.
API response
    │
    ▼
Axios interceptor
    │  401 → call unauthorizedCallback() → redirect to login
    │  all others → pass through as rejected promise
    ▼
TanStack Query cache (onError)
    │  401 → silently ignored (already handled)
    │  403 → toast the server's message, or "Permission denied"
    │  404 → toast "Resource not found"
    │  5xx → toast "Server error — retrying…" / "Server error — please try again"
    │  other status → toast the server's message, or "Request failed (HTTP 409)"
    │  no response → toast "No response from the server" / "The server took too long to respond"
    │  every toast names the request, and a repeat of the same failure updates it
    ▼
Component (optional per-query onError)
    │  Only needed when generic toast is wrong for the specific UX

The 401 Interceptor

Location: src/lib/api/client.ts

The singleton APIClient registers a response interceptor that fires on every request:

this.client.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401 && this.unauthorizedCallback) {
      this.unauthorizedCallback()
    }
    return Promise.reject(error)  // always re-reject so TanStack Query also sees it
  }
)

The unauthorizedCallback is wired to the auth provider's logout/redirect function during initialization. When a 401 arrives:

  1. The callback fires → clears auth state → redirects to the login page.
  2. The error is still re-rejected, so TanStack Query's onError also fires.
  3. The global handler in query-client.ts explicitly silences 401s to avoid a redundant toast on top of the redirect.

Implication for components: Never handle 401 in a component. The interceptor + auth provider handle it globally. Writing per-component 401 handling will race with the redirect and confuse users.


The Global Query Error Handler

Location: src/lib/query-client.ts — handleQueryError function

It is registered on both QueryCache.onError and MutationCache.onError. A query or mutation whose component renders its own error opts out with meta: HANDLES_OWN_ERRORS.

Failure Banner text
Cancelled request (an axios cancel or an aborted fetch), 401 none
403 the server's message (of a JSON body), or Permission denied
404 Resource not found
5xx Server error — retrying… (query), Server error — please try again (mutation)
Any other status (400, 409, 422, …) the server's message (userFacingError, error or message of a JSON body), or Request failed (HTTP 409)
No response (connection failed) No response from the server
No response (the 30 s timeout) The server took too long to respond
An error the application raised (throw new Error('Invalid audit response')) that sentence
A runtime error (TypeError, a schema error, …) The page hit an unexpected error (TypeError)

Under the text, every banner names what failed: the request as POST /qqq/v1/table/order/query (HTTP 409), or While loading records (the query key's namespace in plain words: possibleValues reads possible values) for a query that failed outside a request. The request is written without its query string, and every path segment that is not a plain word (a record id, a UUID, an encoded value) is shown as {id}. Nothing else of the request or response is shown.

One banner per failure. The banner's sonner id is its text plus the request, so a failure that repeats (a polling query that fails on every attempt) updates the banner already on screen instead of adding one. A different failure gets its own banner. A lost connection is one cause whichever request met it, so it has a single banner, which names the request that failed most recently. Without the id every failed poll added a banner, and sonner pauses a toast's timer while the tab is hidden or the pointer rests on the stack, so the banners could pile up.

Console. Each banner is also logged once with console.warn('[API] Request failed:', { context, status, code, name, request, area }): the HTTP status, the axios error code (ERR_NETWORK, ECONNABORTED, ERR_BAD_REQUEST), the error's name, the request as above and the query namespace. It never logs a message, body, header or query string, because those can carry record data.

Implication for components: For most queries and mutations, you do not need onError at all. The global handler covers toasting. Add per-query handling only when you need to do something the global handler cannot — such as mapping a 400 error's field messages back to form fields.


Extracting the Status Code

Location: src/lib/utils/error-utils.ts

import { getErrorStatusCode } from '@/lib/utils/error-utils'

const status = getErrorStatusCode(error)

getErrorStatusCode handles two shapes:

  • AxiosError — reads error.response?.status
  • Plain objects with a numeric status property (e.g. fetch-based wrappers)

Returns undefined for anything else (non-object errors, null, network failures with no response).


Status-by-Status Guide

400 — Validation Error

The global handler toasts the server's message for a 400 (or Request failed (HTTP 400) when it sent none). 400s typically carry field-level validation messages that belong beside individual form fields, so a form handles 400 explicitly, and sets meta: HANDLES_OWN_ERRORS on the mutation when the toast would repeat what the form shows.

import { getErrorStatusCode } from '@/lib/utils/error-utils'

const mutation = useMutation({
  mutationFn: (data: FieldValues) => saveRecord('order', data),
  onError: (error) => {
    if (getErrorStatusCode(error) === 400) {
      // Map backend validation messages to React Hook Form fields
      const fieldErrors = extractFieldErrors(error)  // your helper
      for (const [field, message] of Object.entries(fieldErrors)) {
        form.setError(field, { type: 'server', message })
      }
    }
    // Non-400 errors are already toasted by the global handler
  },
})

If a 400 arrives outside of a form context, add a toast yourself:

onError: (error) => {
  if (getErrorStatusCode(error) === 400) {
    toast.error('Invalid request — please check your input')
  }
}

403 — Permission Denied

The global handler toasts a generic permission-denied message. If the 403 should instead silently hide an action (e.g. a button that should not appear for users without permission), suppress the default behavior by checking permissions from metadata before rendering rather than relying on the API to reject:

// Preferred: hide the action before the user tries it
{tableMetaData.capabilities.includes('insert') && (
  <Button onClick={openCreateModal}>New Record</Button>
)}

If you need custom handling on a 403, use onError and call toast yourself — or do nothing if the generic toast is acceptable.

404 — Not Found

The global handler toasts "Resource not found". For record-view pages where 404 means the record was deleted, render an empty state instead:

const { data: record, error } = useQuery({
  queryKey: queryKeys.tableRecord(tableName, recordId),
  queryFn: () => getRecord(tableName, recordId),
})

if (getErrorStatusCode(error) === 404) {
  return <EmptyState message="This record no longer exists" />
}

The global handler will also toast, which is acceptable — the empty state just provides additional UI context.

5xx — Server Error

The global handler toasts "Server error — retrying…" for queries and "Server error — please try again" for mutations. Queries are automatically retried up to 3 times with exponential back-off (1 s → 2 s → 4 s, max 30 s) before the error surfaces.

No additional per-component handling is needed for 5xx unless you want a custom retry UI or a structured error state for a specific page.

Network Failure (no response)

Treated as non-4xx by the retry logic — queries retry up to 3 times. After all retries are exhausted the global handler toasts "No response from the server" (or "The server took too long to respond" for the 30 s timeout) with the request that failed. No per-component handling needed for the common case.


When to Add Per-Query Error Handling

Add onError to a specific useQuery or useMutation call when:

Scenario What to do
400 with field-level validation messages Map errors to form fields with form.setError()
403 should render empty state instead of toast Catch 403, render empty UI, call toast yourself if the global one also fires
404 should render a structured empty state page Check getErrorStatusCode(error) === 404 and render <EmptyState>
Error should navigate away (e.g. deleted parent record) useRouter().push('/...') in onError
The generic toast message is wrong for this specific action Supply a custom onError that calls toast.error(customMessage)

For all other cases, rely on the global handler and write no error-handling code in the component.


Retry Behavior

The smartRetry function in src/lib/query-client.ts controls when TanStack Query retries:

function smartRetry(failureCount: number, error: unknown): boolean {
  const status = getErrorStatusCode(error)
  // Never retry client errors — they are deterministic
  if (status !== undefined && status >= 400 && status < 500) return false
  // Retry server errors and network failures up to 3 times
  return failureCount < 3
}

Back-off schedule: 1 s → 2 s → 4 s, capped at 30 s.

4xx errors are never retried. There is no per-component way to opt into retrying 4xx errors — that would be intentional since a 400 with bad field data will not resolve itself on retry.


Complete Example — Form with 400 Handling

'use client'

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { saveRecord } from '@/lib/api/tables'
import { queryKeys } from '@/lib/query-client'
import { getErrorStatusCode } from '@/lib/utils/error-utils'

export function EditOrderForm({ orderId, schema, defaultValues }: Props) {
  const queryClient = useQueryClient()
  const form = useForm({ resolver: zodResolver(schema), defaultValues })

  const mutation = useMutation({
    mutationFn: (data: FieldValues) => saveRecord('order', orderId, data),
    onSuccess: () => {
      // Invalidate so the record view refreshes
      queryClient.invalidateQueries({ queryKey: queryKeys.tableRecord('order', orderId) })
      toast.success('Order saved')
    },
    onError: (error) => {
      if (getErrorStatusCode(error) === 400) {
        // Map field errors from the server response body to form fields.
        // The global handler toasts the server's message for a 400; the form
        // places each field's message beside it.
        const body = (error as AxiosError<{ errors: Record<string, string> }>).response?.data
        if (body?.errors) {
          for (const [field, message] of Object.entries(body.errors)) {
            form.setError(field, { type: 'server', message })
          }
        } else {
          toast.error('Please correct the highlighted fields')
        }
        return
      }
      // 401, 403, 404, 5xx, network — already toasted by the global handler
    },
  })

  return (
    <form onSubmit={form.handleSubmit((data) => mutation.mutate(data))}>
      {/* field components */}
    </form>
  )
}

Quick Reference

Layer File Handles
Axios interceptor src/lib/api/client.ts 401 → redirect to login
Global query handler src/lib/query-client.ts Every status but 401, no response, page errors → one toast per failure, naming the request
Per-component onError Your component 400 field errors, custom empty states, navigation
getErrorStatusCode src/lib/utils/error-utils.ts Normalize AxiosError and plain-object errors to HTTP status code