Last active
September 10, 2018 11:31
-
-
Save jmas/8f38d00edf07b469f14326295c8f9cbc to your computer and use it in GitHub Desktop.
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 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