Last active
March 28, 2023 02:58
-
-
Save FranciscoG/de844e841243cfabdbae17a0a1ed9fd2 to your computer and use it in GitHub Desktop.
Wrapping native Fetch to make it mimic Axios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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, | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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