MCPcopy
hub / github.com/unjs/ofetch / createFetchError

Function createFetchError

src/error.ts:21–67  ·  view source on GitHub ↗
(
  ctx: FetchContext<T>
)

Source from the content-addressed store, hash-verified

19export interface FetchError<T = any> extends IFetchError<T> {}
20
21export function createFetchError<T = any>(
22 ctx: FetchContext<T>
23): IFetchError<T> {
24 const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
25
26 const method =
27 (ctx.request as Request)?.method || ctx.options?.method || "GET";
28 const url = (ctx.request as Request)?.url || String(ctx.request) || "/";
29 const requestStr = `[${method}] ${JSON.stringify(url)}`;
30
31 const statusStr = ctx.response
32 ? `${ctx.response.status} ${ctx.response.statusText}`
33 : "<no response>";
34
35 const message = `${requestStr}: ${statusStr}${
36 errorMessage ? ` ${errorMessage}` : ""
37 }`;
38
39 const fetchError: FetchError<T> = new FetchError(
40 message,
41 ctx.error ? { cause: ctx.error } : undefined
42 );
43
44 for (const key of ["request", "options", "response"] as const) {
45 Object.defineProperty(fetchError, key, {
46 get() {
47 return ctx[key];
48 },
49 });
50 }
51
52 for (const [key, refKey] of [
53 ["data", "_data"],
54 ["status", "status"],
55 ["statusCode", "status"],
56 ["statusText", "statusText"],
57 ["statusMessage", "statusText"],
58 ] as const) {
59 Object.defineProperty(fetchError, key, {
60 get() {
61 return ctx.response && ctx.response[refKey];
62 },
63 });
64 }
65
66 return fetchError;
67}

Callers 1

onErrorFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…