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 

Help With AuraHandledExceptions

Hello, I'm trying trow an Aura HandledException, but it doesent work.

Can anyone help me?
Component

public class CEC_SearchAccount{   
    
   public static  void throwException(String Mensagem)
    {
        system.debug('Entra no metho de exception');
        AuraHandledException e = new AuraHandledException(Mensagem);
        e.setMessage(Mensagem);
        system.debug(e);
        throw e;
    }
    
    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('CPF Válido');
                aux_ret= TRUE; 
            }else{
                system.debug('Entra na Excepetion');
                throw new AuraHandledException('CPF Inválido!');
                aux_ret = FALSE;
            }
           
        return aux_ret;
    }
    
    
    
    public static boolean getvalidCNPJ(String CNPJ)
    {
        system.debug('CNPJ informado'+CNPJ);	
        integer value,coeff=2,sum=0,rest=0;
        String dig13,dig14;
             
        //Validar o primeiro digito verificador do CNPJ
        system.debug('Entrou no primeiro for');
        for(integer i = 12; i>0;i--)
        {
            value = Integer.valueOf(CNPJ.substring(i-1,i)) * coeff;
            if(coeff == 9)
            {coeff = 2;
            }else{coeff ++;} 
             
            sum = sum + value;
        
        }
        
        rest =Math.mod(sum,11);
       if((rest == 0) || (rest == 1))
        {
            dig13 = '0';
        }else{
            dig13 = String.valueOf(11 - rest);
        }
        
        
        // Calculando o segundo digito verificador do CNPJ
        
        rest=0;coeff=2;value=0;sum=0;
       
        for(integer i= 13;i>0;i--)
        {
           
            value = Integer.valueOf(CNPJ.substring(i-1,i)) * coeff;
            if(coeff == 9)
            {
              coeff = 2;
            }else{
              coeff ++;
            }    
    
             sum = sum + value;
        }
        
        rest = math.mod(sum,11);
      
        if((rest == 0) || (rest == 1))
        {
            dig14 = '0';
        }else{
            dig14 = String.valueOf(11 - rest);
        }
        
                
        if((CNPJ.substring(12,13) == dig13) && (CNPJ.substring(13,14)== dig14))
        {
             return true;
        }else{
            return false;
        }
    }
    
    @AuraEnabled
    public static List<Account> getvalidKey(String text)
    {
        /*Após ler a string de caracteres, o sistema chama a função de cpf ou cnpj conforme o tamanho da string.
        Caso o cpf/cnpj seja válido realiza a busca no banco*/
        
        boolean ret;
        List<Account> Conta;
        String documentType;
        
        //Caso seja CPF
        if(text.length() == 11)
        {   
            ret = getvalidCPF(text);
            documentType='CPF';
                
        }else if(text.length() == 14) //Caso a string seja um cnpj
        {
            ret = getvalidCNPJ(text);
            documentType = 'CNPJ';
           
        }else{
            system.debug('CPF CNPJ Inválido');//tamanho inválido
        }
        
        //String foi validada pelos digitos verificadores
        if(ret=TRUE)
        {  
            system.debug('Entrou no select');
             Conta   = [Select ID,
                         Name,
                         DocumentType__c,
                         DocumentNumber__c,
                         vlocity_cmt__PremisesId__c,
                         FormattedDocument__c
                         from Account where DocumentNumber__c =:text  AND DocumentType__c =:documentType
                         ];
          
            
            if(Conta.isEmpty())
             {
                 system.debug('Não retorn resultados');
                 throwException('Não houve retorno');
             }
            
            
         }
           
           return Conta;   
        }
   
    }

<aura:component controller="CEC_SearchAccount" implements="force:appHostable">
   
    <aura:attribute name="acctList" type="Object" />
    <lightning:input aura:id="searchText" name="searchText" label="Digite o CPF/CNPJ" />
    <lightning:button variant="brand" label="Buscar" onclick="{!c.handleClick}"/>
    
   <table class="slds-table slds-table--bordered slds-table--striped">
        <thead>
            <tr>
                <th scope="col"><span class="slds-truncate">Nome</span></th>
                <th scope="col"><span class="slds-truncate">Tipo de Documento</span></th>
                <th scope="col"><span class="slds-truncate">Numero de Documento</span></th>
                <th scope="col"><span class="slds-truncate">Documento Formatado</span></th>
                <th scope="col"><span class="slds-truncate">Endereço</span></th>
            </tr>
        </thead>
    <tbody>
    <aura:iteration items="{!v.acctList}" var="a">
        <tr>
        <td>{!a.Name}</td>
        <td>{!a.DocumentType__c}</td>
        <td>{!a.DocumentNumber__c}</td>
        <td>{!a.FormattedDocument__c}</td>
        <td>{!a.vlocity_cmt__PremisesId__c}</td>
        </tr>
    </aura:iteration>
    </tbody>
    </table>
    
<aura:if isTrue="{!v.showError}">
         <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>
({
    
    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"); 
        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"){
                console.log('Entra no IF de Error');
                var errors = response.getError();  
                component.set("v.showErrors",true);
                component.set("v.errorMessage",errors[0].message);
                console.log('Error message:'+component.get("v.errorMessage"));
        }});
        $A.enqueueAction(action);
    }
})


 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Leticia,

Greetings to you!

You need to change a few things in your component. Add these attributes:

<aura:attribute name="errorMessage" type="String" />
<aura:attribute name="showErrors" type="Boolean" />


and change <aura:if isTrue="{!v.showError}">
to <aura:if isTrue="{!v.showErrors}">

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
/*Versão 3.00 - US_179 - Leticia Freitas - 13/11 
Classe que recebe uma string, determina se é um cpf ou um cnpj e a partir dele, realiza a busca dessa conta. 
Caso exista o registro, retorna as informações: Nome, Tipo de Documento (CPF ou CNPJ), Número do documento, Número do Documento Formatado, Logradouro, CEP, Cidade e Estado.
*/

public class CEC_SearchAccount{   
     
    public static List<Account> Conta;
    
    public static List<Account> getfoundAccount(String Key, String documentType)
    {
        system.debug('Entrou na busta de conta');
       Conta  = [Select  Name from Account 
       where DocumentNumber__c =:Key  AND DocumentType__c =:documentType];

        
        if(Conta != NULL)
        {
            system.debug('Tem registros');
        }
            return Conta;
         
          
        
    }
    
    public static void getvalidCPF(String CPF)
    {
        /* Cálcula se o cpf é valido através do cálculo dos digitos validadores.*/
        integer value; 
        integer coeff = 10, sum=0, rest;
        String dig10,dig11;
        
        system.debug('Entrou na getValidCPF');
        
        //Calcula o primeiro digito validador do CPF
        for(integer i=0; i<9;i++)
        {
            system.debug('I: '+ i);
            system.debug('Coeff: '+ coeff);
            value = Integer.valueOf(CPF.substring(i,i+1))* coeff;
            system.debug('Valor da Substring:'+ value);
            coeff--;
            system.debug('Coeff depois do incremento:'+ coeff);
            sum = sum + value ;
            system.debug('Sum:'+ sum);
        }
        
        rest = 11 - math.mod(sum,11);
        system.debug('Resto:'+rest);
        
        if((rest == 10) || (rest == 11))
        {
            dig10 = '0';
        }else{
            dig10 = String.valueOf(rest);
        }
        
        sum = 0;
        coeff = 11;
        value = 0;
        rest =0;
        
        system.debug('Começou a lógica do digito 10');
        for(integer i=0;i<10;i++)
        {
            system.debug('I: '+ i);
            system.debug('Coeff: '+ coeff);
            value = Integer.valueOf(CPF.substring(i,i+1))*coeff;
            coeff--;
            sum = sum + value;
            system.debug('Coeff depois do incremento:'+ coeff);
            system.debug('Soma'+ sum);
        
        }   
        system.debug('Soma fora do loop'+ sum);
        system.debug('Resto antes da função'+rest);
        
        integer restb = math.mod(sum,11);
        rest = 11 - restb;
        
        
        system.debug('Res normal'+rest);
        
        if((rest == 10) || (rest ==11))
        {
            dig11 = '0';
        }else{
            
            dig11=String.valueOf(rest);
            system.debug('Entrou no if do dig 11');
        }
        
        system.debug('CPF dig 11'+cpf.substring(10,11));
        system.debug('CPF dig 10'+cpf.substring(9,10));
        system.debug('DIG 11'+dig11);
        system.debug('DIG 10'+dig10);
        
        // Validate if the calculus match
        if((dig11 == cpf.substring(10,11)) && (dig10 == cpf.substring(9,10)))
        { 
            system.debug('Match');
            String documentType = 'CPF';
            getfoundAccount(CPF,documentType);
        }else{
         system.debug('CNPJ iNVÁLIDO');
        }
    }
    
    
    
    public static void getvalidCNPJ(String CNPJ)
    {
        integer value;
        integer coeff=12,sum,rest;
        String dig13,dig14;
               
        for(integer i = 0; i < 12;i++)
        {
            value = Integer.valueOf(CNPJ.substring(i,1)) * coeff;
            coeff--;
            sum = sum + value;
        }
        
        rest =Math.mod(sum,11);
        
        if((rest == 0) || (rest == 1))
        {
            dig13 = '0';
        }else{
            dig13 = String.valueOf(11 - rest);
        }
        
        // Calculando o segundo digito verificador do CNPJ
        
        rest=0;
        coeff=13;
        
        for(integer i = 0;i<13;i++)
        {
            value = Integer.valueOf(CNPJ.substring(i,1)) * coeff;
            coeff--;
            sum = sum + value;
        }
        
        rest = math.mod(sum,11);
        
        if((rest == 0) || (rest == 1))
        {
            dig14 = '0';
        }else{
            dig14 = String.valueOf(11 - rest);
        }
        
        if((CNPJ.substring(0,13) == dig13) && (CNPJ.substring(0,14)== dig14))
        {
           String documentType ='CNPJ';
            getfoundAccount(CNPJ, documentType);
        }else{
            //
        }
    }
    
    @AuraEnabled
    Public static List<Account> getvalidKey(String text)
    {
        Conta = new List<Account>();
        /*Após ler a string de caracteres, o sistema chama a função de cpf ou cnpj conformo o tamanho da string */
        system.debug('Chegou na função da classe agora o/');
        
        system.debug('Texto:'+text);
        
        system.debug(text.length());
            
        if(text.length() == 11)
        {   system.debug('CPF');
            getvalidCPF(text);
        }else if(text.length() == 14)
        {
            system.debug('CNPJ');
            getvalidCNPJ(text);
        }else{
            system.debug('CPF/CNPJ Inválido');
        }
        if(Conta.isEmpty())
        {
            system.debug('Não retorn resultados');
            throwException('Não houve retorno');
        }
        return conta;
    }
    
 }

Screenshot:

User-added image


I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas