Error handling
A status picker that makes the server answer with 200, 401, 404, 422, 500 or 503. Each failure renders its own state,
server errors get a retry button, and every error is written to a log through the onError callback.
beginneruseFetcherrorstypescript
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch } from "@hyper-fetch/react";
import { useState } from "react";
import type { ApiError, ProblemDetails } from "./api";
import { getStatus } from "./api";
const codes = [200, 401, 404, 422, 500, 503];
type LogEntry = { id: number; time: string; status: number | null; message: string };
let nextLogId = 0;
type ErrorStateProps = {
status: number | null;
error: ProblemDetails | ApiError;
loading: boolean;
onRetry: () => void;
};
/** One place that turns a typed error into UI. Each status gets the message and action that fits it. */
const ErrorState = ({ status, error, loading, onRetry }: ErrorStateProps) => {
// `error` is a union. Only problem details have a `detail` field, so narrow before reading it.
const detail = "detail" in error ? `${error.status}: ${error.detail}` : error.message;
if (status === 401) {
return (
<article className="error">
<h3>Sign in to continue</h3>
<p className="muted">{detail}</p>
<button type="button">Sign in</button>
</article>
);
}
if (status === 404) {
return (
<article className="error">
<h3>Nothing here</h3>
<p className="muted">{detail}</p>
</article>
);
}
// Other 4xx errors repeat on every retry, so there is no retry button.
if (status && status < 500) {
return (
<article className="error">
<h3>The request was rejected</h3>
<p className="muted">{detail}</p>
</article>
);
}
// 5xx, and status 0 for network errors or timeouts, may pass on the next attempt.
return (
<article className="error">
<h3>Something went wrong on our side</h3>
<p className="muted">{detail}</p>
<button type="button" onClick={onRetry} aria-busy={loading} disabled={loading}>
Try again
</button>
</article>
);
};
export const App = () => {
const [code, setCode] = useState(200);
const [log, setLog] = useState<LogEntry[]>([]);
const { data, error, loading, status, refetch, onError } = useFetch(getStatus.setParams({ status: code }));
// Runs for every failed response, refetches included. A good place for toasts, logging or error reporting.
onError(({ response }) => {
const entry = {
id: nextLogId++,
time: new Date().toLocaleTimeString(),
status: response.status,
message: response.error.message,
};
setLog((entries) => [entry, ...entries].slice(0, 8));
});
return (
<main className="container">
<hgroup>
<h1>Error handling</h1>
<p>Pick the status the server answers with. Errors come back typed, in the response, never as a rejection.</p>
</hgroup>
<div role="group">
{codes.map((value) => (
<button
key={value}
type="button"
className={value === code ? undefined : "outline secondary"}
onClick={() => setCode(value)}
>
{value}
</button>
))}
</div>
<div className="grid-2">
<section>
{loading && !data && !error && <article aria-busy="true">Loading...</article>}
{error && <ErrorState status={status} error={error} loading={loading} onRetry={refetch} />}
{data && (
<article>
<h3>Success</h3>
<p>
The server answered <mark>{data.status}</mark> {data.message}.
</p>
</article>
)}
</section>
<article>
<header>
<strong>onError log</strong>
</header>
{log.length === 0 && <p className="muted">No errors yet.</p>}
<ul className="log">
{log.map((entry) => (
<li key={entry.id}>
<small className="muted">{entry.time}</small> <code>{entry.status}</code> {entry.message}
</li>
))}
</ul>
</article>
</div>
</main>
);
};
Run locally
npx tiged BetterTyped/hyper-fetch/examples/react/error-handling hyper-fetch-react-error-handling && cd hyper-fetch-react-error-handling && npm install && npm run devWhat it shows
- A global error type set once on the client with
createClient<{ error: ApiError }>(). - An endpoint error type added with the
errorgeneric. The hook'serroris the union of both. - Errors in the response.
useFetchreturnserrorandstatus; nothing throws and nothing needstry/catch. - A retry button that calls
refetch()for errors that can pass on the next attempt. onErrorruns once per failed response, which is where toasts and error reporting go.
How it works
api.tspasses{ error: ApiError }tocreateClient. Every request of this client can now fail withApiError. HyperFetch returns anErrorfor network failures and timeouts, which also has amessage, so the type holds.getStatusaddserror: ProblemDetails, the body dummyjson sends from/http/:status. The request's error type becomesProblemDetails | ApiError.AppcallsuseFetch(getStatus.setParams({ status: code })). Picking another code changes the params, so the hook sends a new request and clears the previous result.ErrorStatenarrows the union with"detail" in errorbefore reading the problem details, then picks the UI fromstatus: 401 asks to sign in, 404 says nothing is there, other 4xx errors explain the rejection, and 5xx or status0(no response at all) show a "Try again" button wired torefetch.onErrorfrom the hook receives the typed error response. The example keeps the last eight entries in a log.
const { error, status, refetch, onError } = useFetch(getStatus.setParams({ status: code }));
onError(({ response }) => report(response.status, response.error.message));
When to use it
- Any screen where the API can answer with more than one kind of error.
- Apps that report errors to a toast, a log or an error tracker from one place.
Related
Summary
You typed a global error on the client and an endpoint error on one request, rendered a state for each status from the
error the hook returns, retried server errors with refetch() and logged every failure with onError.
