I've built a login panel, which will submit an email and password via fetch/POST. And I wanted to know the best way to handle network status errors?
Reason being, as I want to inject error messages into my login panel for each state/status code.
I've written the code below, which works. But I wondered if there is a better way to write this? For example, should my status code handling go in the catch() etc?
let url = 'www.MYAPI.com/xyz';
// post body data
let data = {
"Username": emailAddress,
"Password": Password,
}
// create request object
let request = new Request(url, {
"method": 'POST',
"mode": 'cors',
"credentials": 'include',
"body": JSON.stringify(data),
"referrerPolicy": "strict-origin-when-cross-origin",
"headers": {
"accept": "application/json, text/plain, */*",
"content-type": "application/json;charset=UTF-8",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
}
});
fetch(request)
.then( async (response) => {
let data = await response.json();
if(response.status === 200){
// LOGIN SUCCESSFUL HERE;
console.log("Successful log in - status: ", data);
document.getElementById("id01").style.display = "none"; // HIDE LOGIN PANEL
} else{
// Rest of status codes (400,500,303), can be handled here appropriately
// IF EMAIL ADDRESS ERROR / STATUS 502
if (data.KnownErrorDescription === "MemberEmailDoesNotExist") {
document.getElementById("email-error").innerHTML = "Please enter a valid email address to sign in";
};
// IF PASSWORD IS EMPTY / STATUS 400
if (data.Message === "The request is invalid.") {
document.getElementById("password-error").innerHTML = data.ModelState["request.Password"][0];
}
// // IF ACCOUNT LOCKED / 502
if (data.KnownErrorDescription === "MemberAccountLocked") {
document.getElementById("failed-sign-in-error").innerHTML = "You need to reset your password";
document.getElementById("password-reset").style.display = "block";
}
};
})
.catch((err) => {
console.log(err);
})