Sending back errors from an Apex server-side controller

Generate and launch a System.AuraHandledException from your Apex controller to transmit a custom error message to a JavaScript controller.

Mistakes occur. Some are anticipated, like flawed input from a user or a duplicate entry in a database. Others are unforeseen, covering a broad range of potential issues encountered during programming.

When errors arise within your Apex controller code, two scenarios emerge. You can handle the error within Apex using a catch block, or the error gets relayed back in the controller’s response.

If you opt to manage the error in Apex, there are two paths you can take. You can address the error in a catch block, possibly recovering from it and providing a regular response to the client. Alternatively, you can create and trigger an AuraHandledException.

The advantage of throwing an AuraHandledException, rather than allowing a system exception to be sent, lies in the opportunity to handle the exception more gracefully in your JavaScript controller code. System exceptions often lack crucial details due to security measures, resulting in the dreaded “An internal server error has occurred…” message. This approach with AuraHandledException allows you to reinsert specific information into the response sent to your client-side code. Moreover, it enables you to choose a more user-friendly message.

Here’s an example of crafting and initiating an AuraHandledException when dealing with erroneous input. Nonetheless, the true advantage of using AuraHandledException emerges when responding to a system exception. For instance, triggering an AuraHandledException upon encountering a DML exception, instead of allowing it to propagate to your client component code, provides significant benefits.

public with sharing class SimpleErrorController {

    static final List<String> BAD_WORDS = new List<String> {
        'bad',
        'words',
        'here'
    };
    
    @AuraEnabled
    public static String helloOrThrowAnError(String name) {

        // Make sure we're not seeing something naughty
        for(String badWordStem : BAD_WORDS) {
            if(name.containsIgnoreCase(badWordStem)) {
                // How rude! Gracefully return an error...
                throw new AuraHandledException('NSFW name detected.');
            }
        }
        
        // No bad word found, so...
        return ('Hello ' + name + '!');
    }
    
}

The JavaScript controller code manages the AuraHandledException triggered by the Apex controller.

({
    "callServer" : function(cmp) {
        var action = cmp.get("c.helloOrThrowAnError");
        action.setParams({ name : "bad" });

        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log("From server: " + response.getReturnValue());
            }
            else if (state === "INCOMPLETE") {
                // do something
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        // log the error passed in to AuraHandledException
                        console.log("Error message: " + 
                                 errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });

        $A.enqueueAction(action);
    }
})

Upon encountering an AuraHandledException thrown by an Apex controller, the JavaScript controller designates the response state as ERROR, allowing retrieval of the error message via processing response.getError().

In this instance, the error is logged to the console. To showcase an error prompt within the UI, employ the lightning:notificationsLibrary component.