From f9dd197f53d2c9d4fb0da31d0cff452823299449 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 1 Mar 2026 16:53:34 +0800 Subject: [PATCH] refactor(types): add unified API response types and error helpers --- dashboard/src/lib/api-helpers.ts | 55 ++++++++++++++++++++++++++++++++ dashboard/src/types/api.ts | 8 +++++ 2 files changed, 63 insertions(+) create mode 100644 dashboard/src/lib/api-helpers.ts create mode 100644 dashboard/src/types/api.ts diff --git a/dashboard/src/lib/api-helpers.ts b/dashboard/src/lib/api-helpers.ts new file mode 100644 index 00000000..a9e429ce --- /dev/null +++ b/dashboard/src/lib/api-helpers.ts @@ -0,0 +1,55 @@ +/** + * API response parsing and error handling helpers + * Provides unified error handling across API modules + */ + +import type { ApiResponse } from '@/types/api' + +/** + * Parse an HTTP response into a typed ApiResponse + * Handles JSON parsing, error extraction, and HTTP status codes + */ +export async function parseResponse(response: Response): Promise> { + if (response.ok) { + try { + const data = await response.json() + return { success: true, data } + } catch { + return { + success: false, + error: 'Failed to parse response body', + } + } + } + + try { + const errorData = await response.json() + const errorMessage = + errorData.error?.detail ?? + errorData.error?.message ?? + errorData.detail ?? + errorData.message ?? + response.statusText + + return { + success: false, + error: String(errorMessage), + } + } catch { + return { + success: false, + error: response.statusText || 'Unknown error', + } + } +} + +/** + * Extract data from successful ApiResponse or throw error + * Simplifies error handling in async functions + */ +export function throwIfError(result: ApiResponse): T { + if (result.success) { + return result.data + } + throw new Error(result.error) +} diff --git a/dashboard/src/types/api.ts b/dashboard/src/types/api.ts new file mode 100644 index 00000000..8727727f --- /dev/null +++ b/dashboard/src/types/api.ts @@ -0,0 +1,8 @@ +/** + * Unified API response type definition + * Discriminated union for type-safe error handling + */ + +export type ApiResponse = + | { success: true; data: T } + | { success: false; error: string }