Skip to main content
3 of 7
added 1444 characters in body
Robs
  • 9.4k
  • 21
  • 119
  • 224

How to Aura Handle multiple DmlExceptions

How should I handle multiple DmlException messages using AuraHandledException

If I do this:

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

I get an unfriendly error message, that the users won't like.

System.DmlException: Update failed. First exception on row 0 with id a0220000005vt34AAA; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION: bla bla bla

If I do this:

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

I get an unfriendly error message which is even worse:

Unknown Error

If I do this:

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

I only get 1 of the DML errors and there could be many.

On the client-side I am using this code to call controller actions and handle errors:

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(cmp, response.getError());
        }
    });
    $A.getCallback(function () {
        $A.enqueueAction(action);
    })();
},
handleErrors: function (cmp, 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();
},

Questions

  1. Is the capability built into the framework to handle multiple DmlException's?
  2. Do I need to write some custom Apex or JavaScript to handle multiple DmlException's?

--

NOTE: this is not a duplicate of this question because he never got a satisfactory answer.

Robs
  • 9.4k
  • 21
  • 119
  • 224