Skip to content

Instantly share code, notes, and snippets.

@SharkFourSix
Created February 20, 2023 22:17
Show Gist options
  • Save SharkFourSix/1e9086955892769c17545d5b46f21fe9 to your computer and use it in GitHub Desktop.
Save SharkFourSix/1e9086955892769c17545d5b46f21fe9 to your computer and use it in GitHub Desktop.
httpstatus.js
(function umd(root, factory) {
root.httpStatus = factory();
})(this, function () {
class StatusEvaluator {
constructor(code) {
this.code = code;
this.map = {};
this.ow = null;
}
when(code, cb) {
this.map[code] = cb
return this;
}
otherwise(cb) {
this.ow = cb
return this;
}
eval() {
if (this.code in this.map) {
this.map[this.code]();
} else {
if (this.ow) {
this.ow()
}
}
}
}
function httpStatus(code) {
return new StatusEvaluator(code)
}
return httpStatus
})
@SharkFourSix
Copy link
Author

Example usage

<script src="/httpstatus.js"></script>
axios.post('/api/login', loginRequest, headers)
                .then(r => doSomething())
                .catch((err) => {
                    httpStatus(err.response.status)
                        .when(401, () => vm.toast('Invalid username or password', 'danger'))
                        .when(403, () => vm.toast('Something went wrong. Please refresh the page', 'danger'))
                        .otherwise(() => vm.toast('Error logging in. Please try again', 'danger'))
                        .eval()
                })
                .finally(() => doSomethingElse())

LICENSE: MIT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment