7

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:

enter image description here

My questions:

  1. 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?
  2. How can I train AuraHandledException to show a nice title not ApexActionError?
  3. Is there any technical reason for requiring to rethrow exceptions for Lightning? And is there a roadmap to make this more convenient.
3
  • 2
    According to this documentation -- developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… you can get more specific error message per each row, f.e. ex.getDmlMessage(0)
    – kurunve
    Feb 27, 2018 at 8:36
  • This challenge never occured to us since we always use a DTO between Apex and lightning. The DTO stores error/success and corresponding messages as well. Feb 27, 2018 at 8:41
  • I found out that we can customize title. showToast event has title parameter and we can set it.
    – javanoob
    Jul 25, 2018 at 0:38

1 Answer 1

5

I just directly rethrow DMLException. They are actually handled properly by the framework. So, my error handling often looks like this:

    try {
        upsert value;
    } catch(DmlException e) {
        throw e;
    } catch(Exception e) {
        throw new AuraHandledException(e.getMessage());
    }

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.

4
  • This means when I just expect a DmlException I don't need to have a try catch at all? Didn't work. The message didn't make it to the UI. And rethrowing it is not much more elegant. Feb 27, 2018 at 16:51
  • Are you talking about a Lightning Apex controller here? Or triggers that run when users are working through LEX in the standard UI. I was assuming the former, but maybe you mean the latter?
    – Aidan
    Feb 28, 2018 at 10:36
  • It are triggers that do addError on multiple record. Feb 28, 2018 at 10:39
  • In that sense, it's just like Classic, isn't it? If your trigger causes an unhandled exception when it's doing DML, you end up with an ugly error in the UI.
    – Aidan
    Feb 28, 2018 at 11:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .