Commit 946930e8 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix error messages rendering as literal "[object Object]"

apiFetch assumed detail was always a string, but FastAPI's own 422
validation errors shape it as a list of {loc, msg, type, ...} objects
- that list became the ApiError's message, and React stringified it
to the literal text "[object Object]" wherever it got rendered (hit
live on prod's Sign up form). Extracts and joins the real msg from
each validation item instead, falling back to the generic status
message when detail isn't a recognizable shape.
parent 20e96ba7
Pipeline #1290 canceled with stages
...@@ -86,6 +86,38 @@ describe('apiFetch', () => { ...@@ -86,6 +86,38 @@ describe('apiFetch', () => {
}) })
}) })
it('extracts a readable message from a FastAPI validation error (detail as an array)', async () => {
// Regression: FastAPI's own 422s shape `detail` as [{loc, msg, type, ...}], not a string -
// unlike every hand-written HTTPException in this backend. The old code assumed detail was
// always a string, so this array ended up as the ApiError's message, and React stringified
// it to the literal text "[object Object]" wherever it got rendered.
vi.mocked(fetch).mockResolvedValueOnce(
jsonResponse(422, {
detail: [{ loc: ['body', 'password'], msg: 'String should have at least 8 characters', type: 'string_too_short' }],
}),
)
await expect(apiFetch('/auth/register')).rejects.toMatchObject({
status: 422,
message: 'String should have at least 8 characters',
})
})
it('joins multiple validation errors together', async () => {
vi.mocked(fetch).mockResolvedValueOnce(
jsonResponse(422, {
detail: [
{ loc: ['body', 'username'], msg: 'Field required', type: 'missing' },
{ loc: ['body', 'password'], msg: 'String should have at least 8 characters', type: 'string_too_short' },
],
}),
)
await expect(apiFetch('/auth/register')).rejects.toMatchObject({
message: 'Field required; String should have at least 8 characters',
})
})
it('falls back to a generic message when the error body is not JSON', async () => { it('falls back to a generic message when the error body is not JSON', async () => {
vi.mocked(fetch).mockResolvedValueOnce(new Response('not json', { status: 500 })) vi.mocked(fetch).mockResolvedValueOnce(new Response('not json', { status: 500 }))
......
...@@ -27,6 +27,24 @@ export function clearTokens() { ...@@ -27,6 +27,24 @@ export function clearTokens() {
localStorage.removeItem(REFRESH_TOKEN_KEY) localStorage.removeItem(REFRESH_TOKEN_KEY)
} }
/** FastAPI's own validation errors (422s) shape `detail` as a list of
* {loc, msg, type, ...} objects, not a string - unlike every hand-written HTTPException in
* this codebase, which always passes a plain string. Rendering that list directly (the old
* behavior here) stringified to the literal text "[object Object]" in the UI. Falls back to
* msg-per-item joined together, or the raw status if detail is missing/some other shape
* entirely. */
function extractErrorMessage(parsedBody: unknown, status: number): string {
const detail = (parsedBody as { detail?: unknown } | null)?.detail
if (typeof detail === 'string') return detail
if (Array.isArray(detail)) {
const messages = detail
.map((item) => (item && typeof item === 'object' && 'msg' in item ? String((item as { msg: unknown }).msg) : null))
.filter((msg): msg is string => !!msg)
if (messages.length > 0) return messages.join('; ')
}
return `Request failed with status ${status}`
}
export class ApiError extends Error { export class ApiError extends Error {
status: number status: number
body: unknown body: unknown
...@@ -118,9 +136,7 @@ export async function apiFetch<T = unknown>(path: string, options: RequestOption ...@@ -118,9 +136,7 @@ export async function apiFetch<T = unknown>(path: string, options: RequestOption
} catch { } catch {
// non-JSON error body, leave parsedBody null // non-JSON error body, leave parsedBody null
} }
const message = throw new ApiError(res.status, extractErrorMessage(parsedBody, res.status), parsedBody)
(parsedBody as { detail?: string } | null)?.detail ?? `Request failed with status ${res.status}`
throw new ApiError(res.status, message, parsedBody)
} }
if (res.status === 204) return undefined as T if (res.status === 204) return undefined as T
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment