[SalesForce] How to display Trigger addError in Salesforce Lightning using AuraException

Background

I have a before insert trigger which returns an error:

myObject.addError('Helpful Message');

Which I want to catch and display gracefully in my lightning component.

My Apex controller handles the error like this:

@AuraEnabled
public static Boolean exampleApexMethod(Id recordId){

    try {
        SomeService.executeSomething(recordId); // fires trigger

    } catch (DmlException de) {
        throw new AuraException(de.getDmlMessage(0));
    } 
    return true;
}

Which is called using this code:

callAction : function(cmp, methodName, params, callback){
    var action = cmp.get(methodName); 
    action.setParams(params);   
    action.setCallback(this, function(response) {
        var state = response.getState();
        if(cmp.isValid() && state === "SUCCESS"){
            var result = response.getReturnValue();
            if (callback) callback(result);
        } else if (state === "ERROR"){
            this.handleErrors(response.getError());                
        }
    });
    $A.getCallback(function() {
        $A.enqueueAction(action); 
    })();  
},

Which uses this error handling function:

handleErrors : function(errors) {
    let toastParams = {
        title: "Error",
        message: "Unknown error", 
        type: "error"
    };
    if (errors) {
        if (errors[0] && errors[0].message) {
            console.log(errors[0].message);
            toastParams.message = errors[0].message;
        }
    }
    let toastEvent = $A.get("e.force:showToast");
    toastEvent.setParams(toastParams);
    toastEvent.fire();
},

Yet, it always displays this message:

An internal server error has occurred Error ID: 2046491801-57672 (119852647)

Rather than:

Helpful Message

Questions

  1. What am I doing wrong?
  2. How can I fix it?

Best Answer

The reason your exceptions come through unhandled is that you are using AuraException. The correct type is AuraHandledException.

Related Topic