Skip to content
34 changes: 27 additions & 7 deletions src/common/atlas/apiClientError.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,41 @@
export class ApiClientError extends Error {
response?: Response;
import { ApiError } from "./openapi.js";

constructor(message: string, response: Response | undefined = undefined) {
export class ApiClientError extends Error {
private constructor(
message: string,
public readonly response?: Response,
public readonly body?: ApiError
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a benefit to us storing the body?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Getting the ApiError model gives us insight into backend error codes, some tools might require an if/else depending on the backend error code.

) {
super(message);
this.name = "ApiClientError";
this.response = response;
}

static async fromResponse(
response: Response,
message: string = `error calling Atlas API`
): Promise<ApiClientError> {
let text: string = "";
let body: ApiError | undefined = undefined;
try {
const text = await response.text();
return new ApiClientError(`${message}: [${response.status} ${response.statusText}] ${text}`, response);
body = (await response.json()) as ApiError;
text = body.reason || "unknown error";
if (body.detail && body.detail.length > 0) {
text = `${text}; ${body.detail}`;
}
} catch {
return new ApiClientError(`${message}: ${response.status} ${response.statusText}`, response);
try {
text = await response.text();
} catch {
text = "";
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we set to something like "couldn't fetch error" or "unknown error" too

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

}
}

if (text.length > 0) {
text = `${message}: [${response.status} ${response.statusText}] ${text.trim()}`;
} else {
text = `${message}: ${response.status} ${response.statusText}`;
}

return new ApiClientError(text, response, body);
}
}
Loading