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
Leticia Monteiro Freitas 4Leticia Monteiro Freitas 4 

Display a Message Error on Lightning Component.

Hello,

I'm trying display a message error on lightning component when i get some error on my apex class, like when my select returns zero records.Or my field doesent have the rigth formatt.

Please, can anyone could help me?

 
Raj VakatiRaj Vakati
Try like this 


Apex Class
 
public with sharing class SampleClass {

    
    @AuraEnabled 
    public static Case resetCase(string recordId){
        
		try{
			
			
		}catch(Exception e){
			
			            throw new AuraHandledException('Error Exception happend'+e.getMessage());           

		}
		
    }
}


COmponent
 
<aura:component controller="SampleClass" access="global">
    
    
     <aura:if isTrue="{!v.showError}">
        <!-- Show the message to ui -->
        <div class="slds-notify slds-notify_toast slds-theme_error">
            <span class="slds-assistive-text">error</span>
            <div class="slds-notify__content">
                <h5 class="slds-text-heading_small slds-align_absolute-center">Error Message </h5>
                <br/>
                <p class="slds-align_absolute-center">{!v.errorMessage}</p>                
            </div>
        </div>
       
    
</aura:component>

In JS controller 
 
doInit: function(component,  event, helper) {
        var recordId = component.get("v.recordId");  
            var action = component.get("c.actioname");
            action.setParams({
                recordId: recordId
            });                 
            action.setCallback(this, function(response){
                var state = response.getState();
                    if (state == "SUCCESS") {
                       // Do action 
                    }
                else if(state == "ERROR"){
                        var errors = response.getError();                       
                            component.set("v.showErrors",true);
                            component.set("v.errorMessage",errors[0].message);
                           
                    }
            });            
            $A.enqueueAction(action);      
        }
    },

 
Leticia Monteiro Freitas 4Leticia Monteiro Freitas 4
Hello Raj, Thanks for replying. 

Still doesnt work for me. Could you help with my code?
 
//meth in controller class

    public static boolean getvalidCPF(String CPF)
    {
        /* Cálcula se o cpf é valido através da fórmula dos digitos validadores.*/
       
        integer value; 
        integer coeff = 10, sum=0, rest;
        String dig10,dig11;
        boolean aux_ret;
        
        //Calcula o primeiro digito validador do CPF
        for(integer i=0; i<9;i++)
        {
            value = Integer.valueOf(CPF.substring(i,i+1))* coeff;
            coeff--;
            sum = sum + value ;
         }
        
        rest = 11 - math.mod(sum,11);
              
        if((rest == 10) || (rest == 11))
        {
            dig10 = '0';
        }else{
            dig10 = String.valueOf(rest);
        }
        
        sum = 0;coeff = 11;value = 0;rest =0; //Zerando os contadores, para validar o próximo digito
        
        //Cálcula o segundo digito validador
        for(integer i=0;i<10;i++)
        {
            value = Integer.valueOf(CPF.substring(i,i+1))*coeff;
            coeff--;
            sum = sum + value;
        }   
        
        integer restb = math.mod(sum,11);
        rest = 11 - restb;
        
        if((rest == 10) || (rest ==11))
        {
            dig11 = '0';
        }else{
            dig11=String.valueOf(rest);
        }
        
             
        // Validar a lógica dos digitos verificadores
     
            if((dig11 == cpf.substring(10,11)) && (dig10 == cpf.substring(9,10)))
            {  system.debug('Valida o IF');
                aux_ret= TRUE; 
            }else{
                system.debug('Entra na Excepetion');
                throw new AuraHandledException('CPF Inválido!');
                aux_ret = FALSE;}
  
        return aux_ret;
    }
 
//component
<aura:component controller="CEC_SearchAccount" implements="force:appHostable">
   
    <aura:attribute name="acctList" type="Object" />
    <aura:attribute name="columns" type="List"/>
   
    <lightning:input aura:id="searchText" name="searchText" label="Digite o CPF/CNPJ" />
    <lightning:button variant="brand" label="Buscar" onclick="{!c.handleClick}"/>
    
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
    <aura:iteration items="{!v.acctList}" var="a">
        <p>{!a.Name}</p>
        <p>{!a.DocumentType__c}</p>
        <p>{!a.DocumentNumber__c}</p>
        <p>{!a.FormattedDocument__c}</p>
        <p>{!a.vlocity_cmt__PremisesId__c}</p>
    </aura:iteration>

     <aura:if isTrue="{!v.showError}">
        <!-- Show the message to ui -->
        <div class="slds-notify slds-notify_toast slds-theme_error">
            <span class="slds-assistive-text">ERROR</span>
            <div class="slds-notify__content">
            <h5 class="slds-text-heading_small slds-align_absolute-center">Error Message </h5>
            <br/>
            <p class="slds-align_absolute-center">{!v.errorMessage}</p>                
            </div>
        </div>
    </aura:if>
</aura:component>
 
//controller js
({
    
    doInit : function(component, event, helper){        
        component.set('v.columnsContas', [
            {label:'Nome', fieldName: 'Name', type: 'text'},
            {label:'Tipo de Documento', fieldname:'DocumentType__c',type:'text'},
            {label:'Número do Documento',fieldname:'DocumentNumber__c',type:'text'},
            {label:'Documento Formatado',fieldname:'FormattedDocument__c',type:'text'},
            {label:'Endereço',fieldname:'vlocity_cmt__PremisesId__c',type:'text'}
        ]);
    },    
 
    
    
    /* Dentro da ação de clicar no botão, a classe controladora aponta para a função validKey*/
       handleClick : function(component, event, helper) {
        var action = component.get("c.getvalidKey"); 
        var input_text = component.find("searchText").get("v.value"); 
        console.log("input_text"+ input_text);
        debugger;
        action.setParams({"text":input_text});
        action.setCallback(this,function(response)
        {
          var state = response.getState();
            
        if(component.isValid() && state=="SUCCESS")
        {
           component.set("v.acctList",response.getReturnValue());
        }else if(state=="ERROR"){
                var errors = response.getError();                       
                component.set("v.showErrors",true);
                component.set("v.errorMessage",errors[0].message);
        }});
        $A.enqueueAction(action);
    }
})

 
Raj VakatiRaj Vakati
Can u give me complete code
Leticia Monteiro Freitas 4Leticia Monteiro Freitas 4
Thanks for the help Raj ! I Get it whats was wrong. 
HariPHariP
Please post your finding. So others can benefit.
 
Gaurav Sinha 27Gaurav Sinha 27
@Raj Vakati
thanks bro your code fulfilled my requirement.

Thanks and regards
Gaurav Sinha
Bennet PallutheBennet Palluthe
I prefer to use the showToast Event (https://developer.salesforce.com/docs/component-library/bundle/force:showToast/documentation) instead of writing a custom solution. 
hairi vickyhairi vicky

So please take and be the Golf Galaxy Survey (https://onlines-feedback.club/)winner to win coupon code.