Error Handling Best Practices for Lightning and Apex

Sending a request from a Lightning component to an Apex Controller and getting back a response is a path that has several potential failure points. Developers sometimes assume for the sake of simplicity that “things will work” and don’t always perform all the proper error checks and handling. In this blog post we look at best practices for handling server-side and client-side errors.

Client-server communication overview

The Lightning Component framework is a client framework. It relies on Apex to perform backend operations such as accessing data.

Exchanges between the two sides follow a common request-response pattern.

  1. A Lightning component sends a request to its Apex controller using a server-side action.
  2. The controller processes the request. This can trigger a server-side error (permission issue, invalid query).
  3. The controller sends a response to the Lightning component.
  4. The Lightning component processes the response in a callback function. This can trigger a client-side error (unexpected response).

If we omit the network-related errors, this pattern can trigger two types of errors that developers must handle: server-side and client-side errors.

Server-side errors

Quick refresher on Apex server-side controller

The Lightning Component framework communicates with Apex via server-side actions. These actions are declared as static methods annotated with @AuraEnabled (documentation).

public with sharing class SimpleServerSideController {

    // Exposing a server-side action to Lightning
    @AuraEnabled
    public static String serverEcho(String firstName) {
        return ('Hello from the server, ' + firstName);
    }
}

What to avoid

Processing a server request can trigger errors due to a variety of causes such as permission issues, invalid queries, or Apex limits being reached. These errors take the form of an Exception being thrown in the Apex code.

If you process a failing server request as is (see code below), a system exception is returned to the Lightning component.

// Bad practice: error message is not user-friendly or informative
@AuraEnabled
public static void triggerInternalError() {
    integer a = 1 / 0; // Division by zero causes exception
}

Doing so is bad practice as this results in a generic error message: “An internal server error has occurred” or “Sorry to interrupt”. This is not user-friendly and provides no information about the error. We all hate that. 🙁

Basic error handling

Thankfully, the solution to this problem is quite simple.

  1. Wrap the code that can trigger exceptions in a try-catch block.
  2. Throw an AuraHandledException in the catch block. This allows you to provide a custom user-friendly error message.

Here is the code of the previous example updated with this best practice.

// Best practice: user-friendly error message provided by an AuraHandledException
@AuraEnabled
public static void triggerBasicAuraHandledError() {
    try {
        integer a = 1 / 0; // Division by zero causes exception
    }
    catch (Exception e) {
        // "Convert" the exception into an AuraHandledException
        throw new AuraHandledException('Darn it! Something went wrong: '
            + e.getMessage());    
    }
    finally {
        // Something executed whether there was an error or not
    }
}

The AuraHandledException is sent back to the client with your custom message, and you’re free to display it in the way you want using the Lightning Component framework.

Custom error handling

The previous solution is good enough for basic error handling, but what if you have a complex processing logic and require more information about the error on the client-side? How about adding an exception name and an error code?

Unfortunately, you cannot extend AuraHandledException to create a custom exception because it is not an extensible Apex class. However, there is a trick that can help you bypass this limitation.

You can add custom data to your AuraHandledException by following these steps.

  1. Create a simple wrapper class that can hold the data.
// Wrapper class for my custom exception data
public class CustomExceptionData {
    public String name;
    public String message;
    public Integer code;

    public CustomExceptionData(String name, String message, Integer code) {
        this.name = name;
        this.message = message;
        this.code = code;
    }
}
  1. Instantiate your custom class, serialize it as JSON, then pass it to the AuraHandledException.
// Throw an AuraHandledException with custom data
CustomExceptionData data = new CustomExceptionData('MyCustomServerError', 'Some message about the error', 123);
throw new AuraHandledException(JSON.serialize(data));
  1. Finally, on the client-side (Lightning controller or helper), parse the error message string as JSON, and access your custom error data.
// Parse custom error data & report it
let errorData = JSON.parse(error.message);
console.error(errorData.name +" (code "+ errorData.code +"): "+ errorData.message);

Client-side errors

Processing a response on the client-side can trigger several types of errors as well. These typically occur when the client receives an answer from the server that does not meet its expectations. This can be caused by a remote technical error such as an AuraHandledException or a value that does not meet certain business rules.

Quick refresher on Lightning Server-Side Actions

The Lightning Component framework uses Server-Side Actions to perform requests on Apex controllers. This is done in five steps.

// Calling a server-side action
({
    callServerSideAction : function(cmp) {
        // 1. Retrieve an action object by specifying the
        //    Apex method that will be called
        let action = cmp.get("c.myApexEndpoint");

        // 2. Optionally set some action parameters
        action.setParams({ firstName : cmp.get("v.firstName") });

        // 3. Configure a callback function that will be
        //    executed to handle the server response
        action.setCallback(this, function(response) {
            // Some response processing code
        });

        // 4. Optionally set some action configuration flags

        // 5. Enqueue the action so that the framework processes it
        $A.enqueueAction(action);
    }
})

For the sake of brevity, we only focus on the callback function in this article. It exposes one argument that is an object holding the response sent by the server.

The first thing to do upon entering the callback function is to check the response state with response.getState(). This function can return different state values, but you should at least check for SUCCESS and ERROR states.

// Server-side action callback
function(response) {
    // Checking the server response state
    let state = response.getState();
    if (state === "SUCCESS") {
        // Process server success response
        let returnValue = response.getReturnValue();
    }
    else if (state === "ERROR") {
        // Process error returned by server
    }
    else {
        // Handle other reponse states
    }
}

Handling a server error

If the state of the response is ERROR, you need to handle a server error. You can access the errors details with the response.getError() function, but there’s a catch: Despite its name, this function returns an array of errors, not just a single one.

In most of the cases, you want to check the first error of this array, but keep in mind that there can be more than one. Here’s the minimal code that covers that.

let errors = response.getError();
let message = 'Unknown error'; // Default error message
// Retrieve the error message sent by the server
if (errors && Array.isArray(errors) && errors.length > 0) {
    message = errors[0].message;
}
// Display the message
console.error(message);

Note that you should avoid using console.log() to report errors. Use console.error() instead. This ensures that your errors are properly reported in your browser’s developer tools. It’s easy to miss an error in a stack full of info or debug messages.

Reporting the error in the console is a start, but the end goal is to display it to the user. The easiest way to do this if you’re working on a page that’s rendered in Lightning Experience is to display a Lightning Toast notification. You can do so by calling the following helper function while passing it the return value of response .getError().

handleErrors : function(errors) {
    // Configure error toast
    let toastParams = {
        title: "Error",
        message: "Unknown error", // Default error message
        type: "error"
    };
    // Pass the error message if any
    if (errors && Array.isArray(errors) && errors.length > 0) {
        toastParams.message = errors[0].message;
    }
    // Fire error toast
    let toastEvent = $A.get("e.force:showToast");
    toastEvent.setParams(toastParams);
    toastEvent.fire();
}

Throwing and catching client-side errors

Client-side errors take the form of a JavaScript Error being thrown. An Error is very similar to Apex Exception: It’s a type built with a constructor, and it supports the same throw-catch syntax.

try {
    // Something that could throw an error
    throw new Error('Error message goes here');
} catch (e) {
    // Error handling
    console.error(e);
} finally {
    // Something executed whether there was an error or not
}

Just like Apex Exceptions, JavaScript Errors enable you to separate result values from errors when you call a function. For instance, if you follow best practices and let your helper do the heavy-lifting, you can write code like this in your controller:

try {
    // Call a function that may throws an Error
    let value = helper.doSomethingThatMightFails();
    // Process value if function succeeded
} catch (e) {
    // Handle error
    console.error(e);
}

Custom client-side errors

If a text message is not enough data to describe your error, you can extend the JavaScript standard Error type and create errors with custom attributes.

// Declaring a custom error type
function MyCustomError(name, message, code) {
    this.name = name;
    this.message = message;
    this.code = code;
    this.stack = (new Error()).stack;
}
MyCustomError.prototype = Object.create(Error.prototype);
MyCustomError.prototype.constructor = MyCustomError;

You can then throw it and catch it with this code.

// Throwing and catching a custom error
try {
    throw new MyCustomError('MyCustomError', 'Custom error message', 456);
} catch (e) {
    if (e instanceof MyCustomError) {
        // Specific message for MyCustomError
        console.error(e.name +' (code '+ e.code +'): '+ e.message);
    }
    else {
        // Generic message for other types of error
        // (unreachable code in this sample)
        console.error(e.message);
    }
}

Closing words

We’ve covered the different types of errors that can occur when processing client-server communications. You now know how to handle those different errors and how to extend them to fit your needs.

How about trying those different options in an interactive playground and studying some sample code?

Resources

Published
September 28, 2017

Leave your comments...

Error Handling Best Practices for Lightning and Apex