Skip to content

Instantly share code, notes, and snippets.

@FranciscoG
Last active March 28, 2023 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FranciscoG/de844e841243cfabdbae17a0a1ed9fd2 to your computer and use it in GitHub Desktop.
Save FranciscoG/de844e841243cfabdbae17a0a1ed9fd2 to your computer and use it in GitHub Desktop.
Wrapping native Fetch to make it mimic Axios
/**
* An extended Error similar to Axios where it includes some of the response information in the error object
* Response type info: https://developer.mozilla.org/en-US/docs/Web/API/Response
*/
export class FetchError extends Error {
response: {
status: Response["status"];
statusText: Response["statusText"];
headers: Response["headers"];
type: Response["type"];
url: Response["url"];
redirected: Response["redirected"];
body: Response["body"];
bodyUsed: Response["bodyUsed"];
};
constructor(msg: string, response: Response) {
super(msg);
this.response = {
status: response.status,
statusText: response.statusText,
headers: response.headers,
type: response.type,
url: response.url,
redirected: response.redirected,
body: response.body,
bodyUsed: response.bodyUsed,
};
}
}
import { FetchError } from './FetchError.ts';
export function fetchLikeAxios(input: URL | Request | string, init?: RequestInit): Promise<Response> {
const response = await fetch(input, init);
if (!response.ok) {
const url = input instanceof Request ? input.url : input
throw new FetchError(`Request to ${url} failed with status ${response.status}`, response);
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment