[SalesForce] Error message from server side controller lightning

Hi i want the error message to be displayed, i am getting value in response.getError() function, i want message argument in this function.
Below is the snippet of how i'm doing, i am getting undefined in str console statement.

JS

  var errors = response.getError();
           if (errors) {
  var str = errors[0].message;
  console.log('str' + JSON.stringify(str));
  component.set("v.Error", str);
  console.log('Here cmp' + component.get("v.Error")); }

Best Answer

Did you try fetching the error as specified in the documentation for Calling a Server Side Actions here.

In your callback:

var state = response.getState();
        // This callback doesn’t reference cmp. If it did,
        // you should run an isValid() check
        //if (cmp.isValid() && state === "SUCCESS") {
        if (state === "SUCCESS") {
            // Alert the user with the value returned 
            // from the server
            alert("From server: " + response.getReturnValue());

            // You would typically fire a event here to trigger 
            // client-side notification that the server-side 
            // action is complete
        }
        //else if (cmp.isValid() && state === "INCOMPLETE") {
        else if (state === "INCOMPLETE") {
            // do something
        }

This is the part that interests you, validate that the state is in Error and fetch the response error message:

        else if (cmp.isValid() && state === "ERROR") {
        else if (state === "ERROR") {
            var errors = response.getError();
            if (errors) {
                if (errors[0] && errors[0].message) {
                    console.log("Error message: " + 
                             errors[0].message);
                }
            } else {
                console.log("Unknown error");
            }
Related Topic