/
ncit
/
c4panelmodel
Обзор
Документация
Войти
/
ncit
/
c4panelmodel
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
src/lib/server/errors.ts
73 строки
2 KB
ncit
feat: rewrite hooks.server.ts to use Supabase Auth
07 июн 2026, 19:32
07 июн 2026, 19:32
b6162ab
Код
Авторство
О чём код?
/** * Centralized error handling for API routes. * * Provides a typed ApiError class and a helper to convert errors into * safe JSON responses. */ import { json } from '@sveltejs/kit'; import { ZodError } from 'zod'; import { logger } from './logger'; export class ApiError extends Error { constructor( public status: number, message: string, public details?: Record<string, string> ) { super(message); this.name = 'ApiError'; } } export function isApiError(err: unknown): err is ApiError { return err instanceof ApiError; } /** * Convert an unknown error into a JSON Response. * Logs the error with context and returns a safe message. */ export function handleApiError(err: unknown, context?: { requestId?: string; method?: string; path?: string }): Response { // Zod validation errors → 400 with field-level details. if (err instanceof ZodError) { const details: Record<string, string> = {}; for (const issue of err.issues) { const field = issue.path.join('.') || '_errors'; details[field] = issue.message; } return json( { error: 'Validation failed', details }, { status: 400 } ); } if (isApiError(err)) { if (err.status >= 500) { logger.error('API error', { ...context, status: err.status, message: err.message, details: err.details }); } return json( { error: err.message, ...(err.details ? { details: err.details } : {}) }, { status: err.status } ); } // SvelteKit HttpError (thrown by error() in guards) — duck-type check. if (typeof err === 'object' && err !== null && 'status' in err && 'body' in err) { const httpErr = err as { status: number; body: { message?: string } }; return json( { error: httpErr.body?.message ?? 'Request failed' }, { status: httpErr.status } ); } // Unexpected error — log full details but return generic message. const message = err instanceof Error ? err.message : String(err); const stack = err instanceof Error ? err.stack : undefined; logger.error('Unhandled API error', { ...context, message, stack }); return json( { error: 'An internal error occurred. Please try again later.' }, { status: 500 } ); }