import { describe, it, expect } from "vitest"; import { AxiosError, AxiosHeaders } from "axios"; import { handleApiError } from "../../src/errorHandler.js"; function makeAxiosError( status: number, statusText: string = "Error" ): AxiosError { const headers = new AxiosHeaders(); const error = new AxiosError("Request failed", "ERR_BAD_REQUEST", undefined, undefined, { status, statusText, headers, config: { headers }, data: {}, }); return error; } function makeTimeoutError(): AxiosError { const error = new AxiosError("timeout of 5000ms exceeded", "ECONNABORTED"); return error; } describe("handleApiError", () => { it("maps 401 to authentication failed message", () => { const result = handleApiError(makeAxiosError(401)); expect(result.isError).toBe(true); expect(result.content[0]).toEqual({ type: "text", text: "[401] Authentication failed. Check DB Planet credentials.", }); }); it("maps 403 to insufficient permissions message", () => { const result = handleApiError(makeAxiosError(403)); expect(result.isError).toBe(true); expect(result.content[0]).toEqual({ type: "text", text: "[403] Insufficient permissions to access this resource.", }); }); it("maps 404 to not found message", () => { const result = handleApiError(makeAxiosError(404)); expect(result.isError).toBe(true); expect(result.content[0]).toEqual({ type: "text", text: "[404] The requested resource was not found.", }); }); it("maps timeout (ECONNABORTED) to timed out message", () => { const result = handleApiError(makeTimeoutError()); expect(result.isError).toBe(true); expect(result.content[0]).toEqual({ type: "text", text: "[TIMEOUT] Request timed out.", }); }); it("maps other HTTP status codes to status + statusText", () => { const result = handleApiError(makeAxiosError(500, "Internal Server Error")); expect(result.isError).toBe(true); expect(result.content[0]).toEqual({ type: "text", text: "[500] Internal Server Error", }); }); it("handles non-Axios errors with message", () => { const result = handleApiError(new Error("Something broke")); expect(result.isError).toBe(true); expect(result.content[0]).toEqual({ type: "text", text: "[ERROR] Something broke", }); }); it("handles unknown non-Error values", () => { const result = handleApiError("string error"); expect(result.isError).toBe(true); expect(result.content[0]).toEqual({ type: "text", text: "[ERROR] An unknown error occurred", }); }); });