Skip to content

Instantly share code, notes, and snippets.

@binaryLady
Created October 12, 2017 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binaryLady/56e7aa1e41d7983f4486fa26dcc279b1 to your computer and use it in GitHub Desktop.
Save binaryLady/56e7aa1e41d7983f4486fa26dcc279b1 to your computer and use it in GitHub Desktop.
Apex class that returns a handled error for Lightning Components
<aura:component controller="FetchDataApexController" implements="force:lightningQuickActionWithoutHeader,force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" extends="c:dataFetch" access="global">
<aura:handler name="loading" event="c:loading" action="{!c.spinnerShow}" />
<aura:handler name="doneloading" event="c:done_loading" action="{!c.spinnerHide}" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="queryList" type="Object[]" default="[]" />
<aura:dependency resource="c:Modal_Dialog" />
<div class="slds">
<div aura:id="optionalModalDialog" />
</div>
</aura:component>
({
getHistoryFunction : function(component, event, helper) {
var selectedAccts = component.get("v.queryList");
var params = {
"acct" : selectedAccts,
};
helper.callServer(component, "c.getDataFromServer", function(response) {
// console.log('response ' + response);
if (!response[0].message && !response.includes('No records')) {
// Process data here if the response does not return an error or
// contain 0 records
} else {
// otherwise display the message (no records returned) if exists
var msg = response[0].message;
if (msg) {
helper.alert(component, 'Error Fetching Data', msg);
} else {
// Or display the handled error returned from the server
helper.alert(component, 'Error Fetching Data', response);
}
}
}, params);
}
})
{(
alert : function(component, title, message) {
$A.createComponent("c:Modal_Dialog", {
"title" : title,
"body" : message,
"cancelLabel" : "",
"onclose" : component.getReference("c.onDestroyModalDialog"),
"oncancel" : component.getReference("c.onDestroyModalDialog"),
"onconfirm" : component.getReference("c.onDestroyModalDialog")
}, function(msgBox) {
// Add the new button to the body array
if (component.isValid()) {
var targetCmp = component.find('optionalModalDialog');
var body = targetCmp.get("v.body");
body.push(msgBox);
targetCmp.set("v.body", body);
}
});
}
})
<aura:component abstract="true" access="global">
<aura:registerEvent name="loading" type="c:loading"/>
<aura:registerEvent name="doneloading" type="c:done_loading"/>
{!v.body}
</aura:component>
({
callServer : function(component,method,callback,params) {
var compEvent = component.getEvent("loading");
compEvent.fire();
var action = component.get(method);
if (params) {
action.setParams(params);
}
action.setCallback(this,function(response) {
var state = response.getState();
console.log('response ' + state);
var values = response.getReturnValue();
//console.log('response keys ' + Object.keys(response));
//console.log('response values ' + Object.values(response))
if (state === "SUCCESS" && values.length != 0) {
callback.call(this,response.getReturnValue());
}
if (state === "ERROR") {
// generic error handler
var errors = response.getError();
if (errors) {
callback.call(this,errors);
console.log("Errors", errors);
compEvent = component.getEvent("doneloading");
compEvent.fire();
}
}
else if(values.length == 0){
callback.call(this,'No records returned from query');
compEvent = component.getEvent("doneloading");
compEvent.fire();
}
compEvent = component.getEvent("doneloading");
compEvent.fire();
});
$A.enqueueAction(action);
}
})
public with sharing class FetchDataApexController {
@AuraEnabled
public static List<sObject> getDataFromServer(List<String> acct){
List<sObject> sObjList = new List<sObject>();
String query = 'SELECT ';
query = query + 'Name, Id, customField__c FROM customObject__c ';
query = query + 'WHERE Id IN: acct ';
query = query + ' ORDER BY CreatedOn__c DESC';
system.debug('query string ' + query);
try{
if(!test.isRunningTest()){
sObjList = Database.query(query);
}
}
catch(system.Exception ex){
system.debug('error ' + ex.getCause());
throw new AuraHandledException('Something went wrong while fetching your records. '+
'This is the error message produded by the system: '+ ex.getMessage());
}
return sObjList;
}
}
@binaryLady
Copy link
Author

This is not a fully implementable example but is intended to show how to pass handled errors from Apex to Lightning... see my blog post for more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment