Skip to content

Instantly share code, notes, and snippets.

@yevmoroz
Last active January 27, 2024 14:38
Show Gist options
  • Save yevmoroz/3e02a136e793207f9b3916804e2183b0 to your computer and use it in GitHub Desktop.
Save yevmoroz/3e02a136e793207f9b3916804e2183b0 to your computer and use it in GitHub Desktop.
basic fetch utils
/**
* Makes fetch call to API
* @param url
* @throws {ApiError}
*/
export const fetchApi = async (url: string) => {
const response = await fetch(url, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new ApiError(response);
}
return await response.json();
};
/**
* Generic ApiError that uses Response from generic fetch to build a meaningful error message
*/
export class ApiError extends Error {
constructor(response: Response) {
super(`Failed fetching URL: ${response.url}`);
this.name = 'ApiError';
this.status = response.status;
this.response = response;
}
status: number;
response: Response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment