My question was previously asked but the answer in that case was unrelated. In my case, I have a class that can raise custom exceptions, and the class may be called from trigger context. When that happens, the calling code doesn't get the custom exception, but instead gets a DMLException. Per the docs, Exception.getCause()
, "Returns the cause of the exception as an exception object," but it's always returning null
. In the debug log, I can see the original exception, for example:
System.DmlException: Update failed. First exception on row 0 with id a56W0000000UCWMIA4; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, FMZ_DisbursementTrigger: execution of AfterUpdate
caused by: FMZ_Loan.InvalidTransactionDateException: New transaction would occur before latest transaction date of: 6/28/2017
FMZ_Loan.InvalidTransactionDateException
is the custom exception I'm trying to detect. For example, from a unit test:
boolean caught = false;
try {
update disb;
}
catch(FMZ_Loan.InvalidTransactionDateException tdEx) {
caught = true; // THIS LINE NEVER REACHED - DMLException instead
}
catch(DMLException dmlEx) {
Exception cause = dmlEx.getCause();
System.assertNotEquals(null, cause); // THIS FAILS
System.assert(cause instanceof FMZ_Loan.InvalidTransactionDateException);
caught = true;
}
System.assert(caught);
This isn't just a testing issue; other code needs to understand why an update may have failed. How do I get the root cause of a DMLException?