Last active
July 18, 2022 11:41
-
-
Save crashmax-dev/68e2447cb420e4f02211ad0fe3a0cfb7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
export default async function fetcher<T = unknown>( | |
input: RequestInfo, | |
init?: RequestInit | |
): Promise<T> { | |
const response = await fetch(input, init) | |
const data = await response.json() as T | |
if (response.ok) { | |
return data | |
} | |
throw new FetchError({ | |
message: response.statusText, | |
response, | |
data | |
}) | |
} | |
export class FetchError extends Error { | |
response: Response | |
data: unknown | |
constructor({ | |
message, | |
response, | |
data | |
}: { | |
message: string | |
response: Response | |
data: unknown | |
}) { | |
super(message) | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(this, FetchError) | |
} | |
this.name = 'FetchError' | |
this.response = response | |
this.data = data ?? { message } | |
} | |
} |
This file contains hidden or 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 fetcher, { FetchError } from './utils/fetcher' | |
interface User { | |
id: number | |
name: string | |
} | |
async function bootstrap() { | |
try { | |
const res = await fetcher<User>('https://..') | |
console.log(res.id) | |
} catch (err) { | |
if (err instanceof FetchError) { | |
console.log(err.message) | |
} | |
} | |
} | |
bootstrap() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment