Skip to content
Open
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
4 changes: 4 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,7 @@ export function createFetchError<T = any>(

return fetchError;
}

export function isFetchError<T = any>(error: unknown): error is FetchError<T> {
return error instanceof FetchError;
}
35 changes: 34 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
} from "vitest";
import { Readable } from "node:stream";
import { H3, HTTPError, readBody, serve } from "h3";
import { $fetch } from "../src/index.ts";
import { $fetch, FetchError, isFetchError } from "../src/index.ts";

describe("ofetch", () => {
let listener: ReturnType<typeof serve>;
Expand Down Expand Up @@ -524,4 +524,37 @@ describe("ofetch", () => {
timeout: 10_000,
});
});

describe("isFetchError", () => {
it("returns true for FetchError instances", async () => {
const error = await $fetch(getURL("404")).catch((error_: any) => error_);
expect(isFetchError(error)).toBe(true);
expect(error).toBeInstanceOf(FetchError);
});

it("returns false for non-FetchError values", () => {
expect(isFetchError(new Error("test"))).toBe(false);
// eslint-disable-next-line unicorn/no-null
expect(isFetchError(null)).toBe(false);
expect(isFetchError(undefined)).toBe(false);
expect(isFetchError("string")).toBe(false);
expect(isFetchError({})).toBe(false);
});

it("narrows type correctly", async () => {
const error: unknown = await $fetch(getURL("403")).catch(
(error_: any) => error_
);
if (isFetchError(error)) {
expect(error.status).toBe(403);
expect(error.statusText).toBe("Forbidden");
expect(error.data).toBeDefined();
expect(error.request).toBeDefined();
expect(error.options).toBeDefined();
expect(error.response).toBeDefined();
} else {
throw new Error("Expected FetchError");
}
});
});
});