简体   繁体   中英

How to handle custom errors from JSON response using JavaScript?

I am trying to print out custom error messages based on the error received in JSON response after using Fetch API.

This is the error message I'm getting after trying to submit data with email that is already in the database:

{"message":"Invalid Request","messages":{"email":["validation.unique"]}}

Here is another error saying email is simply not valid:

{"message":"Invalid Request","messages":{"email":["validation.email"]}}

And I'm trying to print a specific error to the user to say that the email is already in use. I need something like this.

try {
  ...
} catch(error) {
  if(error.message == "validation.unique") {
  ... print error saying email already in use ...
  } elseif(error.message == "validation.email") {
  ... print error saying email is not valid ...
  }
}

How do I check a JSON response in the if statement? The server that's sending the response is using Laravel.

I think you can use 'JSON.parse()'.

function test(tmpJson) {
    var tmpArr = JSON.parse(tmpJson);
    if (tmpArr.message == "Invalid Request") {
        var tmpE = tmpArr.messages.email;
        if (tmpE == "validation.unique") {
            alert('email already in use');
        } else if (tmpE == "validation.email") {
            alert('email is not valid');
        }
    } else {
        //success
    }
}

var testJson = '{"message":"Invalid Request","messages":{"email":["validation.unique"]}}';

test(testJson);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM