Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions src/axiosConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import axios, { AxiosInstance } from "axios";
import { PACKAGE_NAME, PACKAGE_VERSION } from "./contants";
import { PlainlyApiAuthenticationError, PlainlyApiError } from "./sdk/errors";

export function createApiClient(config: {
baseUrl: string;
Expand All @@ -26,14 +27,18 @@ export function createApiClient(config: {
(error) => {
if (error.response) {
const { status, data } = error.response;
const message =
data?.message || `API request failed with status ${status}`;
return Promise.reject({
status,
message,
details: data,
});

// Authentication errors
if (status === 401 || status === 403) {
return Promise.reject(new PlainlyApiAuthenticationError(status));
}

// Other API errors
if (status >= 400 && status < 600) {
return Promise.reject(new PlainlyApiError(status, data?.message));
}
}
// Network or other errors
return Promise.reject(error);
}
);
Expand Down
12 changes: 12 additions & 0 deletions src/sdk/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export class PlainlyApiError extends Error {
constructor(status: number, reason?: string) {
reason = reason || "Please contact support.";
super(`Plainly API error (status ${status}): ${reason}`);
}
}

export class PlainlyApiAuthenticationError extends PlainlyApiError {
constructor(status: number) {
super(status, "Authentication failed. Check your API key.");
}
}