feat: Implement typed error contracts in generic hooks

Introduce discriminated FetchError union type to replace weak string error
handling in API calls and hooks. Enables actionable error diagnostics.

Changes:
- Create types/api.ts with FetchError discriminated union (api_error,
  network_error, abort_error)
- Export type guards: isAuthError, isAbortError, isNetworkError, isApiError
- Update useListData and usePolledData to expose typed FetchError instead of
  string
- Add getErrorMessage() helper to extract displayable messages from FetchError
- Add createStringErrorAdapter() for backward compatibility with string error
  state
- Update handleFetchError() to work with both FetchError and string setters
- Update all consumer hooks to expose typed errors
- Update components to use getErrorMessage() when displaying errors
- Update tests to mock FetchError instead of strings
- Add comprehensive typed error model documentation to Web-Development.md

This enables better error handling patterns:
- Check error.type to distinguish between API, network, and abort errors
- Extract status codes for specific handling (401/403 auth, 50x server errors)
- Maintain backward compatibility with existing string-based error states

All TypeScript compilation passes with no errors.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-28 09:13:47 +02:00
parent 6c8e2b3423
commit 5166789b68
45 changed files with 531 additions and 125 deletions

View File

@@ -43,6 +43,7 @@ export class ApiError extends Error {
* Returns `true` when the error represents an expired or unauthorized session.
*
* @param err - The error returned from the API client.
* @deprecated Use `isAuthError` from `types/api` with discriminated FetchError instead.
*/
export function isAuthError(err: unknown): err is ApiError {
return err instanceof ApiError && (err.status === 401 || err.status === 403);
@@ -78,35 +79,48 @@ export function setUnauthorizedHandler(handler: (() => void) | null): void {
* @param url - Fully-qualified URL.
* @param options - Standard `RequestInit` options.
* @returns Parsed JSON response cast to `T`.
* @throws {ApiError} When the server returns a non-2xx status code.
* @throws {FetchError} When the request fails or server returns non-2xx status.
*/
async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
const response: Response = await fetch(url, {
...options,
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-BanGUI-Request": "1",
...(options.headers as Record<string, string> | undefined),
},
});
try {
const response: Response = await fetch(url, {
...options,
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-BanGUI-Request": "1",
...(options.headers as Record<string, string> | undefined),
},
});
if (!response.ok) {
const body: string = await response.text();
if (!response.ok) {
const body: string = await response.text();
if (response.status === 401 || response.status === 403) {
unauthorizedHandler?.();
if (response.status === 401 || response.status === 403) {
unauthorizedHandler?.();
}
throw new ApiError(response.status, body);
}
throw new ApiError(response.status, body);
}
// 204 No Content — return undefined cast to T.
if (response.status === 204) {
return undefined as unknown as T;
}
// 204 No Content — return undefined cast to T.
if (response.status === 204) {
return undefined as unknown as T;
return (await response.json()) as T;
} catch (error: unknown) {
// Re-throw as-is if already an ApiError (will be converted by caller)
if (error instanceof ApiError) {
throw error;
}
// DOMException with name "AbortError" is an abort — re-throw for caller
if (error instanceof DOMException && error.name === "AbortError") {
throw error;
}
// Other errors (network, JSON parse, etc.)
throw error;
}
return (await response.json()) as T;
}
// ---------------------------------------------------------------------------
@@ -117,7 +131,9 @@ async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
* Perform a GET request to the given path.
*
* @param path - API path relative to `BASE_URL`, e.g. `"/jails"`.
* @param signal - Optional abort signal for request cancellation.
* @returns Parsed response body typed as `T`.
* @throws {FetchError} When the request fails.
*/
export async function get<T>(path: string, signal?: AbortSignal): Promise<T> {
return request<T>(`${BASE_URL}${path}`, { signal });
@@ -130,6 +146,7 @@ export async function get<T>(path: string, signal?: AbortSignal): Promise<T> {
* @param body - Request payload to serialise as JSON.
* @param signal - Optional abort signal for request cancellation.
* @returns Parsed response body typed as `T`.
* @throws {FetchError} When the request fails.
*/
export async function post<T>(path: string, body: unknown, signal?: AbortSignal): Promise<T> {
return request<T>(`${BASE_URL}${path}`, {
@@ -146,6 +163,7 @@ export async function post<T>(path: string, body: unknown, signal?: AbortSignal)
* @param body - Request payload to serialise as JSON.
* @param signal - Optional abort signal for request cancellation.
* @returns Parsed response body typed as `T`.
* @throws {FetchError} When the request fails.
*/
export async function put<T>(path: string, body: unknown, signal?: AbortSignal): Promise<T> {
return request<T>(`${BASE_URL}${path}`, {
@@ -162,6 +180,7 @@ export async function put<T>(path: string, body: unknown, signal?: AbortSignal):
* @param body - Optional request payload.
* @param signal - Optional abort signal for request cancellation.
* @returns Parsed response body typed as `T`.
* @throws {FetchError} When the request fails.
*/
export async function del<T>(path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
return request<T>(`${BASE_URL}${path}`, {