function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ken KoellnerKen Koellner 

Any way to get a DML to commit and then rethrow an Exception and not lose the DML?

I want to report to a caller an error via an Exception but I also want to store a log record in my own error log.  If I rethrow the Exception, my insert DML is always rolled back.  Anyone know a way to get it to stick?

Here's a test sequence I did but the insert is always rolled back.
Class MyException extends Exception {

Exception myEx;

try {
  throw new MyException ('force fail');
} Catch (exception ex) {
  myEx = ex;

if (myex != null) {
  MyLogRecord__c logRecord = new MyLogRecord__c();
  logRecord.message = 'test message';
  insert logRecord;
  savepoint beforeDML = null;
  beforeDML = Database.setSavepoint();
  throw myex;

Ken KoellnerKen Koellner
I heard that doing a savepoint and rolling back will commit everything before the savepoint was created.   That's why I put in beforeDML.  But that didn't help.