1

I want to prevent the exception thrown on the lightning page as below image, and render it as a or to the user. Instead of this Exception / Callback ERROR message , i want to display on my component as a UI:message.

Exception on the screen

Here is what i have tried,

Component :

<aura:component controller="Freight_tableDisplayClass" implements="flexipage:availableForAllPageTypes,force:hasRecordId,force:lightningQuickAction" access="global">
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="messageError" type="Boolean" />
<aura:attribute name="message" type="String"/>
<aura:attribute name="recordId" type="Id" />
<aura:attribute name="lsList" type="Object[]"/>    

<aura:if isTrue="{!v.messageError}">
    <!-- Load error -->
    <div class="userCreateError">
        <ui:message title="Error" severity="error" closable="true">
            <ui:outputText value="{!v.message}"/>
        </ui:message>
    </div>
</aura:if>  

Iteration content:
<aura:iteration items="{!v.lsList}" var="wrap">
    freight weight <ui:outputtext value="{!wrap.weight}"/>    
</aura:iteration>

js controller:

({
    doInit : function(component, event, helper){

        var action = component.get("c.getWrapperlist");

        action.setParams({
            "CaseId" : component.get("v.recordId")
        });
        console.log("caseId :" + component.get("v.recordId"));  

        action.setCallback(this, function(response) {
            var output = response.getReturnValue();
            var latestString = output.LatestStatusString;
            var lsList = JSON.parse(latestString);
            var state = response.getState();
            if(component.isValid() && state === "SUCCESS"){
                component.set("v.lsList",lsList);
            }
            else if(state === "ERROR"){
                var errors = response.getError();
                if (errors[0] && errors[0].message) {
                    component.set("v.message", errors[0].message);
                    component.set("v.messageError", true);
                } 
            }
        });
        $A.enqueueAction(action);
    }
})

Apex Controller:

    global class Freight_tableDisplayClass {

    @AuraEnabled public String LatestStatusString {get;set;}
    @AuraEnabled public Boolean isSuccess { get; set; }
    @AuraEnabled public String msg { get; set; }

    @AuraEnabled
    public static Freight_tableDisplayClass getWrapperlist(Id CaseId)
    {
        list<Freight_AWBResponseParsing.LatestStatus> lsList = new list<Freight_AWBResponseParsing.LatestStatus>();
        Freight_tableDisplayClass obj = new Freight_tableDisplayClass();

        Case caseRecord     = [SELECT Id, Freight_AWB_Number__c, FROM Case WHERE Id =: CaseId];
        Some_Custom_Setting_value__c cs = Some_Custom_Setting_value__c.getValues('someCustomSettingvalue');
        String username     = cs.UserName__c;           
        String password     = cs.Password__c;           

        if(String.isNotBlank(caseRecord.Freight_AWB_Number__c)){
            requestJson = FreightAWBPopUpController.getRequestString(username, password, caseRecord.Freight_AWB_Number__c);
        }
        else{
            obj.msg = 'AWB Freight Number cannot be null';
            obj.isSuccess = false;
            return obj;
        }
        system.debug(' @@ j2Apex.sample string @@ ' + requestJson);
        string endPoint     = cs.Endpoint__c;
        string method       = 'GET';

        try{

            HttpRequest req     = new HttpRequest();
            req.setEndpoint(endPoint);
            req.setMethod(method);
            req.setBody(requestJson);

            Http http           = new Http();
            HTTPResponse res    = http.send(req);

            System.debug('response VALUES' +res.getBody());

            Freight_AWBResponseParsing awbResponseParsed = Freight_AWBResponseParsing.parse(res.getBody());

            // EXCEPTION OCCURS IN THE BELOW LINE - 
            // EXCEPTION Message - System.JSONException: Expected Freight_AWBResponseParsing.ShipmentMilestones but found "" at [line:1, column:2]
            lsList = awbResponseParsed.ShipmentMilestones.shipmentsTracked.history;

            obj.LatestStatusString = JSON.serialize(lsList);

            system.debug(' @@ Latest Status List @@ ' + obj.LatestStatusString);
            //system.debug(' @@ wr Status List @@ ' + obj.aRow);

            return obj;
        }
        catch(JSONException je){
            obj.msg = je.getMessage();
            obj.isSuccess = false;
            return null;
        }

    }
}

1 Answer 1

3

You are not null checking / catching parse errors - you can do this in Javascript as well as Apex.

Try rewriting your callback like this:

action.setCallback(this, function(response) {

  var state = response.getState();
  if(component.isValid() && state === "SUCCESS"){
    var output = response.getReturnValue();
    if (output && output.LatestStatusString){
      var latestString = output.LatestStatusString;
      var lsList = JSON.parse(latestString);
      component.set("v.lsList",lsList);
    }
    else {
      component.set("v.message", "No status found");
      component.set("v.messageError", true);
    }
  }

  //etc...

This way you are preventing any null errors and telling the user no results were found for a null status

2
  • Thanks Caspar for your response. It worked fine. Just a small doubt here, Why do we do an AND check on output and output.LatestStatusString. How that combination returned as a Boolean If condition ?
    – AjaySFDC
    Commented Aug 21, 2017 at 0:51
  • It's a form of lazy evaluation - in this && example, javascript will exit (with result == false ) if the first condition is false, which prevents you from evaluating the second, null condition. You can visualize it as a series of nested if statements if that helps. Commented Aug 21, 2017 at 0:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .