Last active
July 17, 2024 16:27
-
-
Save mattp0123/d257a9c016a142696bdf8fe0767752cc to your computer and use it in GitHub Desktop.
Handle Fetch API error
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
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