diff --git a/src/axiosConfig.ts b/src/axiosConfig.ts index 0d69a61..f7716ab 100644 --- a/src/axiosConfig.ts +++ b/src/axiosConfig.ts @@ -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; @@ -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); } ); diff --git a/src/sdk/errors.ts b/src/sdk/errors.ts new file mode 100644 index 0000000..6cb596c --- /dev/null +++ b/src/sdk/errors.ts @@ -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."); + } +}