Skip to content

Commit 37dc7a6

Browse files
authored
improve error message for failed fetch (commaai#389)
1 parent 6d68147 commit 37dc7a6

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/api/index.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,27 @@ const populateFetchedAt = <T>(item: T): T => {
99
}
1010

1111
export async function fetcher<T>(endpoint: string, init?: RequestInit, apiUrl: string = API_URL): Promise<T> {
12-
const res = await fetch(`${apiUrl}${endpoint}`, {
12+
const req = new Request(`${apiUrl}${endpoint}`, {
1313
...init,
1414
headers: {
1515
...init?.headers,
1616
Authorization: `JWT ${getAccessToken()}`,
1717
},
1818
})
19+
const res = await fetch(req)
1920
const text = await res.text()
21+
if (!res.ok) {
22+
throw new Error(`${req.method} ${req.url} ${res.status}`, { cause: res })
23+
}
2024
// biome-ignore lint/suspicious/noImplicitAnyLet: TODO: validate server response
2125
let json
2226
try {
23-
json = (await JSON.parse(text)) as T & { error?: string; description?: string }
24-
} catch {
25-
throw new Error(`Error: ${res.status} ${res.statusText}`, { cause: text })
27+
json = await JSON.parse(text)
28+
} catch (err) {
29+
throw new Error('Failed to parse response from server', { cause: err })
2630
}
2731
if (json.error) {
28-
throw new Error(json.description, { cause: res })
32+
throw new Error(`Server error: ${json.description}`, { cause: json })
2933
}
3034
if (Array.isArray(json)) {
3135
return json.map(populateFetchedAt) as T

0 commit comments

Comments
 (0)