|
1 | | -export class ApiClientError extends Error { |
2 | | - response?: Response; |
| 1 | +import { ApiError } from "./openapi.js"; |
3 | 2 |
|
4 | | - constructor(message: string, response: Response | undefined = undefined) { |
| 3 | +export class ApiClientError extends Error { |
| 4 | + private constructor( |
| 5 | + message: string, |
| 6 | + public readonly response?: Response, |
| 7 | + public readonly body?: ApiError |
| 8 | + ) { |
5 | 9 | super(message); |
6 | 10 | this.name = "ApiClientError"; |
7 | | - this.response = response; |
8 | 11 | } |
9 | 12 |
|
10 | 13 | static async fromResponse( |
11 | 14 | response: Response, |
12 | 15 | message: string = `error calling Atlas API` |
13 | 16 | ): Promise<ApiClientError> { |
| 17 | + let text: string = ""; |
| 18 | + let body: ApiError | undefined = undefined; |
14 | 19 | try { |
15 | | - const text = await response.text(); |
16 | | - return new ApiClientError(`${message}: [${response.status} ${response.statusText}] ${text}`, response); |
| 20 | + body = (await response.json()) as ApiError; |
| 21 | + text = body.reason || "unknown error"; |
| 22 | + if (body.detail && body.detail.length > 0) { |
| 23 | + text = `${text}; ${body.detail}`; |
| 24 | + } |
17 | 25 | } catch { |
18 | | - return new ApiClientError(`${message}: ${response.status} ${response.statusText}`, response); |
| 26 | + try { |
| 27 | + text = await response.text(); |
| 28 | + } catch { |
| 29 | + text = ""; |
| 30 | + } |
19 | 31 | } |
| 32 | + |
| 33 | + if (text.length > 0) { |
| 34 | + text = `${message}: [${response.status} ${response.statusText}] ${text.trim()}`; |
| 35 | + } else { |
| 36 | + text = `${message}: ${response.status} ${response.statusText}`; |
| 37 | + } |
| 38 | + |
| 39 | + return new ApiClientError(text, response, body); |
20 | 40 | } |
21 | 41 | } |
0 commit comments