Skip to content

Instantly share code, notes, and snippets.

@jmas
Last active September 10, 2018 11:31
Show Gist options
  • Save jmas/8f38d00edf07b469f14326295c8f9cbc to your computer and use it in GitHub Desktop.
Save jmas/8f38d00edf07b469f14326295c8f9cbc to your computer and use it in GitHub Desktop.
class ErrorResponseServiceNotAvailable extends Response {}
class ErrorResponseBackendFailed extends Response {}
class ErrorResponseValidation extends Response {}
class SuccessResponse extends Response {}
// the function
function handleResponse(response) {
if (response.status === 200) {
return new SuccessResponse(response);
}
if (response.status === 400) {
return new ErrorResponseValidation(response);
}
if (response.status > 400) {
return new ErrorResponseBackendFailed(response);
}
if (response.status >= 500) {
throw new ErrorResponseServiceNotAvailable(response);
}
return response;
}
// run!
fetch('...').then(handleResponse).then(response => {
if (response instanceof SuccessResponse) {
// everithing is ok
}
if (response instanceof ErrorResponseValidation) {
// show validation errors
}
if (response instanceof ErrorResponseValidation) {
// something PREDICTABLE goes wrong
}
if (response instanceof ErrorResponseServiceNotAvailable) {
// something UNPREDICTABLE goes wrong
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment