Skip to content

Instantly share code, notes, and snippets.

@mattp0123
Last active July 17, 2024 16:27
Show Gist options
  • Save mattp0123/d257a9c016a142696bdf8fe0767752cc to your computer and use it in GitHub Desktop.
Save mattp0123/d257a9c016a142696bdf8fe0767752cc to your computer and use it in GitHub Desktop.
Handle Fetch API error
class HTTPError extends Error {
constructor(public response: Response) {
super(response.statusText)
this.name = 'HTTPError'
}
}
const abortController = new AbortController()
try {
const response = await fetch('/my-endpoint', {
signal: abortController.signal,
})
if (response.ok) {
const data = await response.json()
// Handle data
} else {
throw new HTTPError(response)
}
} catch (error) {
if (error instanceof TypeError) {
// Handle network error
} else if (error instanceof SyntaxError) {
// Handle JSON parsing error
} else if (error instanceof DOMException) {
// Handle abort error
} else if (error instanceof HTTPError) {
// Handle HTTP error
if (error.response.status === 404) {
// Handle 404 error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment