Skip to content

Instantly share code, notes, and snippets.

@crashmax-dev
Last active July 18, 2022 11:41
Show Gist options
  • Save crashmax-dev/68e2447cb420e4f02211ad0fe3a0cfb7 to your computer and use it in GitHub Desktop.
Save crashmax-dev/68e2447cb420e4f02211ad0fe3a0cfb7 to your computer and use it in GitHub Desktop.
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 }
}
}
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