Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add options field and improve formatting of errors #270

Merged
merged 18 commits into from
Aug 23, 2023
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ const { users } = await ofetch("/api/users", {
Parsed error body is available with `error.data`. You may also use `FetchError` type.

```ts
await ofetch("http://google.com/404");
// FetchError: 404 Not Found (http://google.com/404)
await ofetch("https://google.com/404");
// FetchError: [GET] "https://google/404": 404 "Not Found"
// at async main (/project/playground.ts:4:3)
```

Expand Down
33 changes: 21 additions & 12 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { FetchRequest, FetchResponse } from "./fetch";
import type { FetchOptions, FetchRequest, FetchResponse } from "./fetch";

export class FetchError<T = any> extends Error {
name = "FetchError";
request?: FetchRequest;
options?: FetchOptions;
response?: FetchResponse<T>;
data?: T;
status?: number;
Expand All @@ -13,20 +14,23 @@ export class FetchError<T = any> extends Error {

export function createFetchError<T = any>(
request: FetchRequest,
options: FetchOptions,
error?: Error,
response?: FetchResponse<T>
): FetchError<T> {
let message = "";
if (error) {
message = error.message;
}
if (request && response) {
message = `${message} (${response.status} ${
response.statusText
} (${request.toString()}))`;
} else if (request) {
message = `${message} (${request.toString()})`;
}
const errorMessage = error?.message || error?.toString() || "";

const method = (request as Request)?.method || options?.method || "GET";
const url = (request as Request)?.url || String(request) || "/";
const requestStr = `[${method}] ${JSON.stringify(url)}`;

const statusStr = response
? `${response.status} ${JSON.stringify(response.statusText)}`
: "<no response>";

const message = `${requestStr}: ${statusStr}${
errorMessage ? ` ${errorMessage}` : ""
}`;

const fetchError: FetchError<T> = new FetchError(message);

Expand All @@ -35,6 +39,11 @@ export function createFetchError<T = any>(
return request;
},
});
Object.defineProperty(fetchError, "options", {
get() {
return options;
},
});
Object.defineProperty(fetchError, "response", {
get() {
return response;
Expand Down
1 change: 1 addition & 0 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
// Throw normalized error
const error = createFetchError(
context.request,
context.options,
context.error,
context.response
);
Expand Down
17 changes: 14 additions & 3 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@ import {
readRawBody,
toNodeListener,
} from "h3";
import { Blob } from "fetch-blob";
import { FormData } from "formdata-polyfill/esm.min.js";
import { describe, beforeAll, afterAll, it, expect } from "vitest";
import { Headers, $fetch } from "../src/node";
import { Headers, FormData, Blob } from "node-fetch-native";
import { $fetch } from "../src/node";

describe("ofetch", () => {
let listener;
Expand Down Expand Up @@ -253,6 +252,18 @@ describe("ofetch", () => {
expect(abortHandle()).rejects.toThrow(/aborted/);
});

it("passing request obj should return request obj in error", async () => {
const error = await $fetch(getURL("/403"), { method: "post" }).catch(
(error) => error
);
expect(error.toString()).toBe(
'FetchError: [POST] "http://localhost:3000/403": 403 "Forbidden"'
);
expect(error.request).to.equal(getURL("403"));
expect(error.options.method).to.equal("POST");
expect(error.response?._data).to.deep.eq(error.data);
});

it("aborting on timeout", async () => {
const noTimeout = $fetch(getURL("timeout")).catch(() => "no timeout");
const timeout = $fetch(getURL("timeout"), {
Expand Down