✨ enhance error handling and localization in API responses
Browse files at this commitee0b44df115331cb946752ff7dcf507b410811d0Parent: bb43cea- feat
- ✨ enhance error handling and localization in API responses
9 changed files +69 -24
- src/api/client.ts +57 -4
- src/components/exams/exam-card.tsx +1 -1
- src/components/marks/marks-report-view.tsx +1 -1
- src/components/ui/select.tsx +1 -1
- src/pages/course-detail-page.tsx +3 -5
- src/pages/dashboard-page.tsx +1 -1
- src/pages/event-detail-page.tsx +2 -4
- src/pages/exam-detail-page.tsx +1 -3
- src/pages/exam-room-page.tsx +2 -4
src/api/client.tsmodified+57 -4
| @@ -21,6 +21,38 @@ type RequestOptions = { | |||
| 21 | const API_PREFIX = "/api"; | 21 | const API_PREFIX = "/api"; |
| 22 | 22 | ||
| 23 | const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = { | 23 | const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = { |
| 24 | + "request failed": { | ||
| 25 | + en: "Request failed.", | ||
| 26 | + tr: "İşlem tamamlanamadı.", | ||
| 27 | + }, | ||
| 28 | + "unauthorized": { | ||
| 29 | + en: "Sign in to continue.", | ||
| 30 | + tr: "Devam etmek için giriş yap.", | ||
| 31 | + }, | ||
| 32 | + "forbidden": { | ||
| 33 | + en: "You do not have permission for this action.", | ||
| 34 | + tr: "Bu işlem için yetkin yok.", | ||
| 35 | + }, | ||
| 36 | + "not found": { | ||
| 37 | + en: "The requested record was not found.", | ||
| 38 | + tr: "İstenen kayıt bulunamadı.", | ||
| 39 | + }, | ||
| 40 | + "invalid credentials": { | ||
| 41 | + en: "Username or password is incorrect.", | ||
| 42 | + tr: "Kullanıcı adı veya şifre hatalı.", | ||
| 43 | + }, | ||
| 44 | + "username already exists": { | ||
| 45 | + en: "This username is already in use.", | ||
| 46 | + tr: "Bu kullanıcı adı zaten kullanılıyor.", | ||
| 47 | + }, | ||
| 48 | + "course not found": { | ||
| 49 | + en: "Course not found.", | ||
| 50 | + tr: "Ders bulunamadı.", | ||
| 51 | + }, | ||
| 52 | + "exam not found": { | ||
| 53 | + en: "Exam not found.", | ||
| 54 | + tr: "Sınav bulunamadı.", | ||
| 55 | + }, | ||
| 24 | "not enrolled in this exam's course": { | 56 | "not enrolled in this exam's course": { |
| 25 | en: "You are not enrolled in this exam's course.", | 57 | en: "You are not enrolled in this exam's course.", |
| 26 | tr: "Bu sınavın dersine kayıtlı değilsin.", | 58 | tr: "Bu sınavın dersine kayıtlı değilsin.", |
| @@ -43,6 +75,17 @@ const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = { | |||
| 43 | }, | 75 | }, |
| 44 | }; | 76 | }; |
| 45 | 77 | ||
| 78 | +function currentLocale(): Locale { | ||
| 79 | + if (typeof window === "undefined") return "en"; | ||
| 80 | + try { | ||
| 81 | + const saved = window.localStorage.getItem("hezarfen.locale"); | ||
| 82 | + if (saved === "en" || saved === "tr") return saved; | ||
| 83 | + return window.navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en"; | ||
| 84 | + } catch { | ||
| 85 | + return "en"; | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 46 | function normalizeApiMessage(message: string): string { | 89 | function normalizeApiMessage(message: string): string { |
| 47 | return message | 90 | return message |
| 48 | .trim() | 91 | .trim() |
| @@ -93,7 +136,9 @@ export async function client<T>(path: string, options: RequestOptions = {}): Pro | |||
| 93 | const message = | 136 | const message = |
| 94 | data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string" | 137 | data && typeof data === "object" && "error" in data && typeof (data as { error: unknown }).error === "string" |
| 95 | ? (data as { error: string }).error | 138 | ? (data as { error: string }).error |
| 96 | - : res.statusText || "Request failed"; | 139 | + : data && typeof data === "object" && "message" in data && typeof (data as { message: unknown }).message === "string" |
| 140 | + ? (data as { message: string }).message | ||
| 141 | + : res.statusText || "Request failed"; | ||
| 97 | 142 | ||
| 98 | let retryAfter: number | null = null; | 143 | let retryAfter: number | null = null; |
| 99 | if (res.status === 429) { | 144 | if (res.status === 429) { |
| @@ -110,15 +155,23 @@ export async function client<T>(path: string, options: RequestOptions = {}): Pro | |||
| 110 | return data as T; | 155 | return data as T; |
| 111 | } | 156 | } |
| 112 | 157 | ||
| 113 | -export function formatApiErrorMessage(message: string, locale: Locale = "en"): string { | 158 | +export function formatApiErrorMessage(message: string, locale: Locale = currentLocale()): string { |
| 114 | - return API_ERROR_MESSAGES[normalizeApiMessage(message)]?.[locale] ?? sentenceCase(message); | 159 | + const normalized = normalizeApiMessage(message); |
| 160 | + const known = API_ERROR_MESSAGES[normalized]?.[locale]; | ||
| 161 | + if (known) return known; | ||
| 162 | + if (locale === "tr") return "İşlem tamamlanamadı. Lütfen tekrar dene."; | ||
| 163 | + return sentenceCase(message); | ||
| 115 | } | 164 | } |
| 116 | 165 | ||
| 117 | -export function formatApiError(err: unknown, locale: Locale = "en"): string { | 166 | +export function formatApiError(err: unknown, locale: Locale = currentLocale()): string { |
| 118 | if (err instanceof ApiError) { | 167 | if (err instanceof ApiError) { |
| 119 | if (err.status === 429 && err.retryAfter != null) { | 168 | if (err.status === 429 && err.retryAfter != null) { |
| 120 | return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`; | 169 | return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`; |
| 121 | } | 170 | } |
| 171 | + if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale]; | ||
| 172 | + if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale]; | ||
| 173 | + if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale]; | ||
| 174 | + if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again."; | ||
| 122 | return formatApiErrorMessage(err.message, locale); | 175 | return formatApiErrorMessage(err.message, locale); |
| 123 | } | 176 | } |
| 124 | if (err instanceof Error) return formatApiErrorMessage(err.message, locale); | 177 | if (err instanceof Error) return formatApiErrorMessage(err.message, locale); |
src/components/exams/exam-card.tsxmodified+1 -1
| @@ -52,7 +52,7 @@ export function ExamCard(props: { exam: Exam; courseTitle?: string; now?: number | |||
| 52 | }; | 52 | }; |
| 53 | 53 | ||
| 54 | return ( | 54 | return ( |
| 55 | - <Link to="/exams/$id" params={() => ({ id: props.exam.id })} class="group block h-full"> | 55 | + <Link to="/exams/$id" params={{ id: props.exam.id }} class="group block h-full"> |
| 56 | <article class="surface-card relative flex h-full min-h-52 flex-col overflow-hidden transition-all group-hover:-translate-y-0.5 group-hover:border-rose-500/30 group-hover:shadow-sm"> | 56 | <article class="surface-card relative flex h-full min-h-52 flex-col overflow-hidden transition-all group-hover:-translate-y-0.5 group-hover:border-rose-500/30 group-hover:shadow-sm"> |
| 57 | <div class="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-rose-500/70 via-amber-400/50 to-transparent" /> | 57 | <div class="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-rose-500/70 via-amber-400/50 to-transparent" /> |
| 58 | <div class="flex flex-1 flex-col p-4"> | 58 | <div class="flex flex-1 flex-col p-4"> |
src/components/marks/marks-report-view.tsxmodified+1 -1
| @@ -68,7 +68,7 @@ export function MarksReportView(props: { report: MarksReport }) { | |||
| 68 | {(entry) => ( | 68 | {(entry) => ( |
| 69 | <TableRow> | 69 | <TableRow> |
| 70 | <TableCell> | 70 | <TableCell> |
| 71 | - <Link to="/exams/$id" params={() => ({ id: entry.exam })} class="font-medium hover:underline"> | 71 | + <Link to="/exams/$id" params={{ id: entry.exam }} class="font-medium hover:underline"> |
| 72 | {entry.title} | 72 | {entry.title} |
| 73 | </Link> | 73 | </Link> |
| 74 | </TableCell> | 74 | </TableCell> |
src/components/ui/select.tsxmodified+1 -1
| @@ -10,7 +10,7 @@ export function Select(props: SelectProps) { | |||
| 10 | return ( | 10 | return ( |
| 11 | <select | 11 | <select |
| 12 | class={cn( | 12 | class={cn( |
| 13 | - "flex h-9 w-full rounded-sm border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50", | 13 | + "flex h-9 w-full rounded-sm border border-input bg-background px-3 py-1 text-sm text-foreground shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>option]:bg-popover [&>option]:text-popover-foreground", |
| 14 | local.class, | 14 | local.class, |
| 15 | )} | 15 | )} |
| 16 | {...rest} | 16 | {...rest} |
src/pages/course-detail-page.tsxmodified+3 -5
| @@ -9,7 +9,7 @@ import { getMyCourses } from "@/api/getMyCourses"; | |||
| 9 | import { patchCourseById } from "@/api/patchCourseById"; | 9 | import { patchCourseById } from "@/api/patchCourseById"; |
| 10 | import { postCourseEnrollment } from "@/api/postCourseEnrollment"; | 10 | import { postCourseEnrollment } from "@/api/postCourseEnrollment"; |
| 11 | import { postCourseExam } from "@/api/postCourseExam"; | 11 | import { postCourseExam } from "@/api/postCourseExam"; |
| 12 | -import { ApiError, formatApiError } from "@/api/client"; | 12 | +import { formatApiError } from "@/api/client"; |
| 13 | import { ExamForm } from "@/components/exams/exam-form"; | 13 | import { ExamForm } from "@/components/exams/exam-form"; |
| 14 | import { RouteGuard } from "@/components/layout/route-guard"; | 14 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 15 | import { PageHeader } from "@/components/layout/page-header"; | 15 | import { PageHeader } from "@/components/layout/page-header"; |
| @@ -129,9 +129,7 @@ function CourseDetailContent() { | |||
| 129 | when={course()} | 129 | when={course()} |
| 130 | fallback={ | 130 | fallback={ |
| 131 | <Show when={course.error}> | 131 | <Show when={course.error}> |
| 132 | - <Alert variant="destructive"> | 132 | + <Alert variant="destructive">{formatApiError(course.error)}</Alert> |
| 133 | - {course.error instanceof ApiError ? course.error.message : t("common.notFound")} | ||
| 134 | - </Alert> | ||
| 135 | </Show> | 133 | </Show> |
| 136 | } | 134 | } |
| 137 | > | 135 | > |
| @@ -345,7 +343,7 @@ function CourseDetailContent() { | |||
| 345 | <li> | 343 | <li> |
| 346 | <Link | 344 | <Link |
| 347 | to="/exams/$id" | 345 | to="/exams/$id" |
| 348 | - params={() => ({ id: exam.id })} | 346 | + params={{ id: exam.id }} |
| 349 | class="group flex items-start justify-between gap-3 rounded-lg border border-border/70 bg-background/60 px-4 py-3 transition-all hover:-translate-y-0.5 hover:border-primary/30 hover:bg-accent/35 hover:shadow-sm" | 347 | class="group flex items-start justify-between gap-3 rounded-lg border border-border/70 bg-background/60 px-4 py-3 transition-all hover:-translate-y-0.5 hover:border-primary/30 hover:bg-accent/35 hover:shadow-sm" |
| 350 | > | 348 | > |
| 351 | <div class="min-w-0 space-y-2"> | 349 | <div class="min-w-0 space-y-2"> |
src/pages/dashboard-page.tsxmodified+1 -1
| @@ -249,7 +249,7 @@ function DashboardContent() { | |||
| 249 | <li> | 249 | <li> |
| 250 | <Link | 250 | <Link |
| 251 | to="/exams/$id" | 251 | to="/exams/$id" |
| 252 | - params={() => ({ id: exam.id })} | 252 | + params={{ id: exam.id }} |
| 253 | class="flex min-h-[3.5rem] items-center justify-between gap-3 rounded-lg border border-border/70 bg-muted/25 px-3 py-2.5 transition-colors hover:border-primary/35 hover:bg-primary/[0.05]" | 253 | class="flex min-h-[3.5rem] items-center justify-between gap-3 rounded-lg border border-border/70 bg-muted/25 px-3 py-2.5 transition-colors hover:border-primary/35 hover:bg-primary/[0.05]" |
| 254 | > | 254 | > |
| 255 | <div class="min-w-0"> | 255 | <div class="min-w-0"> |
src/pages/event-detail-page.tsxmodified+2 -4
| @@ -6,7 +6,7 @@ import { getEventAttendance } from "@/api/getEventAttendance"; | |||
| 6 | import { getEventById } from "@/api/getEventById"; | 6 | import { getEventById } from "@/api/getEventById"; |
| 7 | import { patchEventById } from "@/api/patchEventById"; | 7 | import { patchEventById } from "@/api/patchEventById"; |
| 8 | import { postEventAttendance } from "@/api/postEventAttendance"; | 8 | import { postEventAttendance } from "@/api/postEventAttendance"; |
| 9 | -import { formatApiError, ApiError } from "@/api/client"; | 9 | +import { formatApiError } from "@/api/client"; |
| 10 | import type { AttendanceStatus } from "@/api/types"; | 10 | import type { AttendanceStatus } from "@/api/types"; |
| 11 | import { AttendanceStatusPicker } from "@/components/events/attendance-status-picker"; | 11 | import { AttendanceStatusPicker } from "@/components/events/attendance-status-picker"; |
| 12 | import { AttendanceTable } from "@/components/events/attendance-table"; | 12 | import { AttendanceTable } from "@/components/events/attendance-table"; |
| @@ -79,9 +79,7 @@ function EventDetailContent() { | |||
| 79 | when={event()} | 79 | when={event()} |
| 80 | fallback={ | 80 | fallback={ |
| 81 | <Show when={event.error}> | 81 | <Show when={event.error}> |
| 82 | - <Alert variant="destructive"> | 82 | + <Alert variant="destructive">{formatApiError(event.error)}</Alert> |
| 83 | - {event.error instanceof ApiError ? event.error.message : t("common.notFound")} | ||
| 84 | - </Alert> | ||
| 85 | </Show> | 83 | </Show> |
| 86 | } | 84 | } |
| 87 | > | 85 | > |
src/pages/exam-detail-page.tsxmodified+1 -3
| @@ -174,9 +174,7 @@ function ExamDetailContent() { | |||
| 174 | when={exam()} | 174 | when={exam()} |
| 175 | fallback={ | 175 | fallback={ |
| 176 | <Show when={exam.error}> | 176 | <Show when={exam.error}> |
| 177 | - <Alert variant="destructive"> | 177 | + <Alert variant="destructive">{formatApiError(exam.error)}</Alert> |
| 178 | - {exam.error instanceof ApiError ? exam.error.message : t("common.notFound")} | ||
| 179 | - </Alert> | ||
| 180 | </Show> | 178 | </Show> |
| 181 | } | 179 | } |
| 182 | > | 180 | > |
src/pages/exam-room-page.tsxmodified+2 -4
| @@ -2,7 +2,7 @@ import { Link, useParams } from "@tanstack/solid-router"; | |||
| 2 | import { Show, Suspense, createResource } from "solid-js"; | 2 | import { Show, Suspense, createResource } from "solid-js"; |
| 3 | import { getExamById } from "@/api/getExamById"; | 3 | import { getExamById } from "@/api/getExamById"; |
| 4 | import { getMyCourses } from "@/api/getMyCourses"; | 4 | import { getMyCourses } from "@/api/getMyCourses"; |
| 5 | -import { ApiError } from "@/api/client"; | 5 | +import { formatApiError } from "@/api/client"; |
| 6 | import { ExamRoomWS } from "@/components/exams/exam-room-ws"; | 6 | import { ExamRoomWS } from "@/components/exams/exam-room-ws"; |
| 7 | import { RouteGuard } from "@/components/layout/route-guard"; | 7 | import { RouteGuard } from "@/components/layout/route-guard"; |
| 8 | import { PageHeader } from "@/components/layout/page-header"; | 8 | import { PageHeader } from "@/components/layout/page-header"; |
| @@ -46,9 +46,7 @@ function ExamRoomContent() { | |||
| 46 | when={exam()} | 46 | when={exam()} |
| 47 | fallback={ | 47 | fallback={ |
| 48 | <Show when={exam.error}> | 48 | <Show when={exam.error}> |
| 49 | - <Alert variant="destructive"> | 49 | + <Alert variant="destructive">{formatApiError(exam.error)}</Alert> |
| 50 | - {exam.error instanceof ApiError ? exam.error.message : t("common.notFound")} | ||
| 51 | - </Alert> | ||
| 52 | </Show> | 50 | </Show> |
| 53 | } | 51 | } |
| 54 | > | 52 | > |