Returning Errors from an Apex Server-Side Controller

Create and throw a System.AuraHandledException from your server-side controller to return a custom error message.

Errors happen. Sometimes they’re expected, such as invalid input from a user, or a duplicate record in a database. Sometimes they’re unexpected, such as... Well, if you’ve been programming for any length of time, you know that the range of unexpected errors is nearly infinite.

When your server-side controller code experiences an error, two things can happen. You can catch it there and handle it in Apex. Otherwise, the error is passed back in the controller’s response.

If you handle the error Apex, you again have two ways you can go. You can process the error, perhaps recovering from it, and return a normal response to the client. Or, you can create and throw an AuraHandledException.

The benefit of throwing AuraHandledException, instead of letting a system exception be returned, is that you have a chance to handle the exception more gracefully in your client code. System exceptions have important details stripped out for security purposes, and result in the dreaded “An internal server error has occurred…” message. Nobody likes that. When you use an AuraHandledException you have an opportunity to add some detail back into the response returned to your client-side code. More importantly, you can choose a better message to show your users.

Here’s an example of creating and throwing an AuraHandledException in response to bad input. However, the real benefit of using AuraHandledException comes when you use it in response to a system exception. For example, throw an AuraHandledException in response to catching a DML exception, instead of allowing that to propagate down to your client component code.
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 + '!');
    }
    
}