12
Apr

Error Handling in Lightning & Apex

Sailfin 0 comment

Error handling is the process comprising of anticipation, detection and resolution of application errors, programming errors or communication errors. It is one of the most important and overlooked topic for programmers, regardless of the language used.

In programming, a development error can occur due to syntax or logic. In computer science, a syntax error is an error in the syntax of a sequence of characters or tokens that is intended to be written in a programming language. A logical error is a bug in the program that causes it to operate incorrectly but does not crash the system.

In Salesforce, sending a request from a Salesforce Lightning component to an Apex Controller and getting back a response is a path that has several potential failure points. These errors can be Server side or Client side. Server-side errors:

Whenever we are using any logic at the server side, we need to catch errors properly and display them on screen. To achieve this –

  • Wrap the code in a try-catch block.
  • Throw an AuraHandledException in the catch block, it will display proper error at component level.

Example: Avoid writing code without exception handling like below snippet

public with sharing class ApexController {

// Method for error

@AuraEnabled

public static void showError() {

integer divideByZero = 1 / 0;

}

} Updated snippet and best practice for previous example: public with sharing class ApexController {

// Method for error

@AuraEnabled

public static void showError() {

try {

integer divideByZero = 1 / 0;

} catch (Exception e) {

throw new AuraHandledException(e.getMessage());

}

}

} Client-side errors:

In Lightening JavaScript, we must handle unrecoverable and recoverable app errors.

An unrecoverable exception is mostly runtime exception like Null Pointer Exception. They are usually the result of some missed checks in the program code.

A recoverable exception is something that you know beforehand can happen and take certain measures.

To handle these errors, use try-catch and a component such as ui:message to tell users about the problem. Example: This example shows how unrecoverable error prevents your app from executing successfully.

<!–c: unrecoverableError –>

<aura:component >

<lightning:button label=”throw error” onclick=”{!c.throwError}”/>

</aura:component>

/*unrecoverableErrorController.js*/

({

throwError : function(component, event){

throw new Error(“Hi Tej Pal, this is Unrecoverable Error”);

}

}) Updated snippet and best practice for previous example: <!–c:recoverableError–>

<aura:component >

<div aura:id=”div1″></div>

<lightning:button label=”Throw an Error” onclick=”{!c.throwErrorForKicks}”/>

</aura:component>

/*recoverableErrorController.js*/

({

throwErrorForKicks: function(cmp) {

// this sample always throws an error to demo try/catch

var hasPerm = false;

try {

if (!hasPerm) {

throw new Error(“You don’t have permission to edit this record.”);

}

}

catch (e) {

$A.createComponents([

[“ui:message”,{

“title” : “Sample Thrown Error”,

“severity” : “error”,

}],

[“ui:outputText”,{

“value” : e.message

}]

],

function(components, status, errorMessage){

if (status === “SUCCESS”) {

var message = components[0];

var outputText = components[1];

// set the body of the ui:message to be the ui:outputText

message.set(“v.body”, outputText);

var div1 = cmp.find(“div1”);

// Replace div body with the dynamic component

div1.set(“v.body”, message);

}else if (status === “INCOMPLETE” || status === “ERROR”) {

console.log(“Error: ” + errorMessage);

}

}

);

}

}

})

In summation, use try-catch blocks to catch all errors for an invisible process that you generally intend to fail, and use other, more appropriate methods when you need to be precise. The larger the try-catch block, the more errors you may be masking, so use try-catch only to catch exceptions and try to keep them as small as possible.

*** Happy Coding ***