Exception handling in Lightning is a pain. Instead of Lightning showing regular exceptions one has to catch them in code and rethrow them as AuraHandledExceptions
as shown below:
try {
....
update records;
}
catch(DmlException ex) {
throw new AuraHandledException(ex.getMessage());
}
Especially in cases of DmlExceptions
that can contain multiple errors (one per record) the output is more than ugly:
My questions:
- How can I just show the message of the original first error (the blurry part in my screenshot without all the techie stuff in front of it?
- How can I train AuraHandledException to show a nice title not ApexActionError?
- Is there any technical reason for requiring to rethrow exceptions for Lightning? And is there a roadmap to make this more convenient.
Best Answer
I just directly rethrow
DMLException
. They are actually handled properly by the framework. So, my error handling often looks like this:If there is a
DMLException
, it arrives in Lightning as a structured error object where you can split those errors up into multiple message if you want to.It would be nice if
AuraHandledException
had more methods so that we could add structure to custom errors, but I can't find any ability to do that.