Created
May 18, 2021 18:40
-
-
Save NotFounds/417cb9c47bc49dd9f94f1645a31d33dd to your computer and use it in GitHub Desktop.
fetch API wrapper to handle HTTP errors
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
const handleHttpErrors = (response: Response) => { | |
if (response.ok || response.redirected) { | |
return response; | |
} | |
// ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status | |
switch (response.status) { | |
// Client error responses | |
case 400: throw Error('Bad Request'); | |
case 401: throw Error('Unauthorized'); | |
case 402: throw Error('Payment Required'); | |
case 403: throw Error('Forbidden'); | |
case 404: throw Error('Not Found'); | |
case 405: throw Error('Method Not Allowed'); | |
case 406: throw Error('Not Acceptable'); | |
case 407: throw Error('Proxy Authentication Required'); | |
case 408: throw Error('Request Timeout'); | |
case 409: throw Error('Conflict'); | |
case 410: throw Error('Gone'); | |
case 411: throw Error('Length Required'); | |
case 412: throw Error('Precondition Failed'); | |
case 413: throw Error('Payload Too Large'); | |
case 414: throw Error('URI Too Long'); | |
case 415: throw Error('Unsupported Media Type'); | |
case 416: throw Error('Range Not Satisfiable'); | |
case 417: throw Error('Expectation Failed'); | |
case 418: throw Error('I\'m a teapot'); | |
case 421: throw Error('Misdirected Request'); | |
case 422: throw Error('Unprocessable Entity'); | |
case 423: throw Error('Locked'); | |
case 424: throw Error('Failed Dependency'); | |
case 425: throw Error('Too Early'); | |
case 426: throw Error('Upgrade Required'); | |
case 428: throw Error('Precondition Required'); | |
case 429: throw Error('Too Many Requests'); | |
case 431: throw Error('Request Header Fields Too Large'); | |
case 451: throw Error('Unavailable For Legal Reasons'); | |
// Server error responses | |
case 500: throw Error('Internal Server Error'); | |
case 501: throw Error('Not Implemented'); | |
case 502: throw Error('Bad Gateway'); | |
case 503: throw Error('Service Unavailable'); | |
case 504: throw Error('Gateway Timeout'); | |
case 505: throw Error('HTTP Version Not Supported'); | |
case 506: throw Error('Variant Also Negotiates'); | |
case 507: throw Error('Insufficient Storage'); | |
case 508: throw Error('Loop Detected'); | |
case 510: throw Error('Not Extended'); | |
case 511: throw Error('Network Authentication Required'); | |
default: throw Error('Unexpected Error'); | |
} | |
}; | |
export const fetchWithError = (input: RequestInfo, init?: RequestInit | undefined): Promise<Response> => { | |
return fetch(input, init) | |
.catch((e) => { throw Error(e); }) | |
.then(handleHttpErrors) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment