Skip to content

Instantly share code, notes, and snippets.

@vastus
Created April 23, 2018 12:35
Show Gist options
  • Select an option

  • Save vastus/45acc9e8cfcea8673d60aee5fe0cc18f to your computer and use it in GitHub Desktop.

Select an option

Save vastus/45acc9e8cfcea8673d60aee5fe0cc18f to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>redir</title>
</head>
<body>
<input id="input" type="number" value="403" />
<button id="button">Action</button>
<script>
const checkStatus = (resp) => {
if (resp.ok === false) {
return Promise.reject({ code: '50x', message: 'response failed' });
}
switch (resp.status) {
case 403:
console.log('reject!');
return Promise.reject({ code: 403, message: 'invalid token or whatever' });
default:
return resp;
}
};
const parseJSON = (resp) =>
resp.json();
const handleError = (err) => {
console.log('handleError', err);
if (err.code && err.code === 403) {
return window.location.replace('https://yle.fi');
}
}
const handleClick = (statusCodeInput, e) => {
const statusCode = parseInt(statusCodeInput.value, 10);
console.log(statusCode);
Promise
.resolve({ status: statusCode, json: () => { return { id: 42 }; }})
.then(checkStatus)
.then(parseJSON)
.then(console.log)
.catch(handleError)
// window.location.replace('https://yle.fi');
};
const eInput = document.getElementById('input');
const eButton = document.getElementById('button');
eButton.addEventListener('click', handleClick.bind(null, eInput));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment