function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Øyvind Borgersen 10Øyvind Borgersen 10 

Lightning component warning message

Hi,

I need to display a warning or error message on lightning page based on various logic from an apex class. This should be updated dynamically based on the different logic. 

F.ex the apex class runs a check on  a custom email field on the case record to check if the email exist in a contact related to the account. If it exist but no portal user is created for that account we should display a warning message as a lightning component. If custom email address does not match any contacts then there should be an error message.

How can we setup a dynamically error/warning  message for this?
Best Answer chosen by Øyvind Borgersen 10
Ahmed Ansari 13Ahmed Ansari 13
for apex class your method like
public class apexController { 
    @AuraEnabled public static Boolean isEmailExist(String customEmail){
        List<Contact> con = [Select Id From Contact where email =:customEmail];
        if(con.size()>0)
        return true;
        else 
        return false
 return null;
    }
    
 }

and Js Controller 
CheckEmail : function(component, event, helper) {
        var action = component.get('c.isEmailExist'); 
       
        action.setParams({
            "customEmail" : component.get('v.Email');
        });
        action.setCallback(this, function(a){
            var state = a.getState(); // get the response state
            if(state == 'SUCCESS') {
                component.set('v.boolean', a.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }

All Answers

Ahmed Ansari 13Ahmed Ansari 13

hello 

For this you use 

<aura:attribute name="boolean" type="boolean" default="false"/>
<aura:if isTrue="{!v.boolean}">
<!-- everything in here is rendered if boolean is true -->
</aura:if>

Øyvind Borgersen 10Øyvind Borgersen 10
Thanks Ahmed,

How would the controller code be based on this?
Ahmed Ansari 13Ahmed Ansari 13
for apex class your method like
public class apexController { 
    @AuraEnabled public static Boolean isEmailExist(String customEmail){
        List<Contact> con = [Select Id From Contact where email =:customEmail];
        if(con.size()>0)
        return true;
        else 
        return false
 return null;
    }
    
 }

and Js Controller 
CheckEmail : function(component, event, helper) {
        var action = component.get('c.isEmailExist'); 
       
        action.setParams({
            "customEmail" : component.get('v.Email');
        });
        action.setCallback(this, function(a){
            var state = a.getState(); // get the response state
            if(state == 'SUCCESS') {
                component.set('v.boolean', a.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
This was selected as the best answer
Øyvind Borgersen 10Øyvind Borgersen 10
Thanks Ahmed!
Deepali KulshresthaDeepali Kulshrestha
Hi Øyvind,
Whenever we are using any logic at the server side, we need to catch errors properly and display them on screen. To achieve this –

Wrap the code in a try-catch block.
Throw an AuraHandledException in the catch block, it will display proper error at component level.
Example: Avoid writing code without exception handling like below snippet

public with sharing class ApexController {

// Method for error

@AuraEnabled

public static void showError() {

integer divideByZero = 1 / 0;

}

}
 public with sharing class ApexController {

// Method for error

@AuraEnabled

public static void showError() {

try {

integer divideByZero = 1 / 0;

} catch (Exception e) {

throw new AuraHandledException(e.getMessage());

}

}


Client-side errors:

In Lightening JavaScript, we must handle unrecoverable and recoverable app errors.

An unrecoverable exception is mostly runtime exception like Null Pointer Exception. They are usually the result of some missed checks in the program code.

A recoverable exception is something that you know beforehand can happen and take certain measures.

To handle these errors, use try-catch and a component such as ui:message to tell users about the problem. Example: This example shows how unrecoverable error prevents your app from executing successfully.

<!–c: unrecoverableError –>

<aura:component >

<lightning:button label=”throw error” onclick=”{!c.throwError}”/>

</aura:component>

/*unrecoverableErrorController.js*/

({

throwError : function(component, event){

throw new Error(“Hi Tej Pal, this is Unrecoverable Error”);

}

})
<!–c:recoverableError–>

<aura:component >

<div aura:id=”div1?></div>

<lightning:button label=”Throw an Error” onclick=”{!c.throwErrorForKicks}”/>

</aura:component>

/*recoverableErrorController.js*/

({

throwErrorForKicks: function(cmp) {

// this sample always throws an error to demo try/catch

var hasPerm = false;

try {

if (!hasPerm) {

throw new Error(“You don’t have permission to edit this record.”);

}

}

catch (e) {

$A.createComponents([

[“ui:message”,{

“title” : “Sample Thrown Error”,

“severity” : “error”,

}],

[“ui:outputText”,{

“value” : e.message

}]

],

function(components, status, errorMessage){

if (status === “SUCCESS”) {

var message = components[0];

var outputText = components[1];

// set the body of the ui:message to be the ui:outputText

message.set(“v.body”, outputText);

var div1 = cmp.find(“div1”);

// Replace div body with the dynamic component

div1.set(“v.body”, message);

}else if (status === “INCOMPLETE” || status === “ERROR”) {

console.log(“Error: ” + errorMessage);

}

}

);

}

}

})

Please refer to the following link as it may be helpful in solving your issue:
https://salesforce.stackexchange.com/questions/247721/display-apex-error-message-in-lightning-component
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha