When we use an Apex Controller method in lightning JS Controller or Helper, sometimes error occurs on execution of apex method. In lightning response object though the state value comes as ERROR but the message in the error object always says ‘Internal Server Error”. Here is an example to handle the apex exception and how to show custom messages in Lightning Component.
In below example I’ve used Lead object FirstName, LastName, Email & Company Field. In lead object LastName & Company fields are required. If we will submit the form without the required fields, then the apex method will throw the error message, which we can show in lightning component or we can add our custom message there.
Apex Controller:
public class SampleAuraController {
@AuraEnabled
Public static void createLead(Lead objLead){
try{
//Insert Lead Record
insert objLead;
}catch(DmlException e) {
//get DML exception message
throw new AuraHandledException(e.getMessage());
}catch(Exception e){
//get exception message
throw new AuraHandledException(e.getMessage());
}
finally {
}
}
}
({
//Handle Lead Save
handleLeadSave : function(component, event, helper) {
var objLead = component.get("v.objLead");
var action = component.get("c.createLead");
action.setParams({
objLead : objLead
});
action.setCallback(this,function(a){
var state = a.getState();
if(state === "SUCCESS"){
alert('Record is Created Successfully');
} else if(state === "ERROR"){
var errors = action.getError();
if (errors) {
if (errors[0] && errors[0].message) {
alert(errors[0].message);
}
}
}else if (status === "INCOMPLETE") {
alert('No response from server or client is offline.');
}
});
$A.enqueueAction(action);
}
})
When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup. But we can use StandardController.addFields(List fieldNames) method, which adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as well.
public with sharing class AccountControllerExt {
public Account acc {get; set;}
public AccountControllerExt(ApexPages.StandardController controller) {
List<String> accFieldList = new List<String>();
//Passing a list of field names to the standard controller
controller.addFields(new List<String>{'Id', 'Name', 'AccountNumber', 'Website', 'Phone','Type', 'Industry'});
//Standard controller to retrieve the field data of the record
acc = (Account)controller.getRecord();
}
}
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject