You need to sign in to do that
Don't have an account?
Leticia Monteiro Freitas 4
Help With AuraHandledExceptions
Hello, I'm trying trow an Aura HandledException, but it doesent work.
Can anyone help me?
Component
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); } })
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.
Screenshot:
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