( ctx: FetchContext<T> )
| 19 | export interface FetchError<T = any> extends IFetchError<T> {} |
| 20 | |
| 21 | export 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 | } |
no outgoing calls
no test coverage detected
searching dependent graphs…