| 62 | } |
| 63 | |
| 64 | async function toApiError(res: Response): Promise<ApiError> { |
| 65 | let message = `Request failed with status ${res.status}`; |
| 66 | try { |
| 67 | const body = (await res.json()) as { error?: string; message?: string }; |
| 68 | message = body.error ?? body.message ?? message; |
| 69 | } catch { |
| 70 | // ignore parse errors |
| 71 | } |
| 72 | |
| 73 | const type = |
| 74 | res.status === 401 |
| 75 | ? "auth" |
| 76 | : res.status === 404 |
| 77 | ? "not_found" |
| 78 | : res.status === 429 |
| 79 | ? "rate_limit" |
| 80 | : res.status >= 500 |
| 81 | ? "server" |
| 82 | : "server"; |
| 83 | |
| 84 | const retryAfterMs = |
| 85 | res.status === 429 |
| 86 | ? (parseInt(res.headers.get("Retry-After") ?? "60", 10) || 60) * 1_000 |
| 87 | : undefined; |
| 88 | |
| 89 | return new ApiError(res.status, message, type, retryAfterMs); |
| 90 | } |
| 91 | |
| 92 | // --------------------------------------------------------------------------- |
| 93 | // ApiClient |