4

I need to execute a future method (with callout) when an exception is caught, at the same time, just after that, I need to thrown another custom exception. It seems both things can not play together...following some pieces of code to clarify the behavior

    try {
        uow.commitWork();
    }catch (DmlException e){
        deleteAppoitment(calendarProviderEventId, requestDTO.selectedAgentId);
        throw new AppointmentException('My custom error message');
    }

Where:

@Future(Callout=true)
private static void deleteAppoitment(String calendarProviderEventId, String userId) {
    //Do Something
}

Is there any option to do it? or the only thing I can do is returning null instead of the throwing the custom exception...?

1 Answer 1

5

Throwing an uncaught exception fully reverts the state of the database, including future methods, sending emails, schedulable, queueable, etc. The only exception to this is the EventBus.publish method, when the Platform Event is set to "Deliver Immediately." This is the only mechanism you can use to perform additional asynchronous work and throw an uncaught exception.

try {
    uow.commitWork();
}catch (DmlException e){
    DeleteEvent__e deleteEvent = new DeleteEvent__c(ProviderEventId__c=calendarProviderEventId, SelectedAgentId__c=requestDTO.selectedAgentId);
    EventBus.publish(deleteEvent);
    throw new AppointmentException('My custom error message');
}

From there, you can define a trigger to do additional logic:

trigger DeleteEventHandler on DeleteEvent__e(after insert) {
  // Perform your desired logic here
}

These triggers don't count against daily Platform Event limits.

You can read more about Platform Events in the docs.

1
  • 1
    Amazing! Working perfectly! Good to know! Nov 10, 2021 at 19:04

You must log in to answer this question.

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