Build an OpenWAApiError from a fetch Response, awaiting its body.
(res: Response, context: string)
| 41 | |
| 42 | /** Build an {@link OpenWAApiError} from a fetch Response, awaiting its body. */ |
| 43 | static async fromResponse(res: Response, context: string): Promise<OpenWAApiError> { |
| 44 | // An opaque unfollowed redirect (we set `redirect: 'manual'`) surfaces as status 0, not a 3xx. |
| 45 | // Give it a clear message instead of "OpenWA API 0": the redirect was deliberately not followed |
| 46 | // so the API key is never re-sent to the redirect target. |
| 47 | if (res.status === 0) { |
| 48 | return new OpenWAApiError( |
| 49 | `Unexpected redirect (not followed; the API key is never re-sent to a redirect target) — ${context}`, |
| 50 | 0, |
| 51 | undefined, |
| 52 | ); |
| 53 | } |
| 54 | let body: unknown = undefined; |
| 55 | const text = await res.text().catch(() => ''); |
| 56 | if (text) { |
| 57 | try { |
| 58 | body = JSON.parse(text); |
| 59 | } catch { |
| 60 | body = text; |
| 61 | } |
| 62 | } |
| 63 | const env = isNestEnvelope(body) ? body : undefined; |
| 64 | const messageText = describeMessage(env?.message ?? body ?? res.statusText); |
| 65 | const message = `OpenWA API ${res.status} ${res.statusText} — ${context}: ${messageText}`; |
| 66 | return new OpenWAApiError(message, res.status, body, env?.error); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /** 401 Unauthorized — missing or invalid API key. */ |
no test coverage detected