Display Apex Exception message nicely in Lightning toast

Adding ugly wrapping code to all my @AuraEnabled methods seemed not to be an acceptable clean solution to me...

@AuraEnabled
public static Id myAction() {
   try {
      // regular action code
   }
   catch (Exception ex){
      throw new AuraHandledException(ex.getMessage());
   }
 }

...so I solved it in my JS toast code.

var uglyIndicator = "Caused by: common.apex.runtime.impl.ExecutionException:";
if(message.includes(uglyIndicator)) {
    message = message.split(uglyIndicator)[1];
}

I suppose, in case, when system exception could be thrown you need to throw it one more time, but as a AuraHandledException. Something like:

try {
    Decimal result = 322 / 0;
} catch (Exception ex){
    throw new AuraHandledException(ex.getMessage());
}

There's a particular apex class called an AuraHandledException that you need to use to Return Errors from an Apex Server-Side Controller.

Note that you need to set the message through the class constructor rather than using the Exception.setMessage() method.

// This goes to the ui
AuraHandledException e = new AuraHandledException('Message I want to display');

// This message stays server-side
e.setMessage('Message I want to display');