How should I handle multiple DmlException
messages when using AuraHandledException
inside an Apex Controller.
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 JavaScript 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();
},
I cannot find the defacto solution or framework best practice for handling what must be a common scenario.
Ideally, I'd like a solution which can be used in the Apex controller.
Questions
- Is there a capability built into the Lightning framework to handle multiple
DmlException
's? - Should the JavaScript handle the
DmlException
rethrow differently? - Do I need to write some custom Apex to handle multiple
DmlException
's?
--
NOTE: this is not a duplicate of this question because he never got a satisfactory answer.
e.getDmlMessage
to throw all errors in a loop or concatenate them?AuraHandledException
doesn't work as expected and spits out ugly exception.