1
\$\begingroup\$

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);
  })
\$\endgroup\$
3
  • \$\begingroup\$ Welcome to the Code Review Community. The title of the question should be an introduction into what the code does, not your concerns about the code. Please read How do I ask a good question?. \$\endgroup\$
    – pacmaninbw
    May 9, 2021 at 11:47
  • 1
    \$\begingroup\$ The way you're handling the errors looks just fine to me. Because the fetch() API doesn't throw on bad status codes, there's no good way to handle the errors in the catch block, unless you threw them from your .then() handler, which is an option, but it's not needed. \$\endgroup\$ May 20, 2021 at 3:36
  • \$\begingroup\$ @ScottyJamison - Thank you for the feedback! Appreciate! \$\endgroup\$ May 20, 2021 at 14:41

1 Answer 1

1
\$\begingroup\$

I personally think that You can easily handle part of the error handling logic in the catch block however at the moment You are listening for the specific response status do specify what went wrong during the API connection process.

MDN says:

You can use a catch block to handle all exceptions that may be generated in the try block.

try/catch works in a way that if anything fails on the try block, then the rest of the code (in the try block) is ignored and the script execution goes to the catch block. If something goes wrong then the error object is created and passed to the catch block as a parameter .catch(err). From this object You might be able to handle part of the error handling logic. Take a look at the below links:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch https://javascript.info/try-catch

Moreover:

let data = {
    "Username": emailAddress,
    "Password": Password,
  }

can be changed like so (get rid of capital letters here)

let data = {
    username: emailAddress,
    password: password
  }

so that You can change it to

let data = {
    username: emailAddress,
    password
  }
\$\endgroup\$
4
  • \$\begingroup\$ Hey @AdamKniec, sorry for the delay in coming back to you and I appreciate your feedback! I'm just wrapping up a project and I shall come back to you in the next day or two. I appreciate your feedback. I have a couple of questions but not urgent, thank you! \$\endgroup\$ May 20, 2021 at 11:57
  • \$\begingroup\$ Hey @AdamKniec - thank you for the feedback? I wondered why the url and data variable should be a const? Thank you! \$\endgroup\$ May 20, 2021 at 14:43
  • 1
    \$\begingroup\$ @ReenaVerma because values assigned to those variables does not change. In that case its a good prsctice to use a const. It uses less memory in the CPU \$\endgroup\$
    – AdamKniec
    May 20, 2021 at 14:44
  • \$\begingroup\$ Thank you! Really helpful note on its impact on CPU. I had no idea that was the case. \$\endgroup\$ May 20, 2021 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.