Making an HTTP callout after rolling back DML Operations
You can now make an HTTP callout after rolling back DML operations by releasing savepoints with Database.releaseSavepoint.
The introduction of the Database.releaseSavepoint method in Salesforce Apex is a significant development because traditionally, once you rolled back a transaction to a savepoint, you couldn't make any future DML operations or callouts in that transaction. This limitation poses a challenge in complex transactional scenarios where you may need to perform a callout after a conditional rollback.
Here's an example of how Database.releaseSavepoint can be used:Savepoint sp = Database.setSavepoint();
try
// ... some logic that may fail
} catch (Exception ex) {
// Exception handling if needed
Database.rollback(sp);
Database.releaseSavepoint(sp); // Also releases any savepoints created after 'sp'
// Since savepoint is released, you can now make a callout
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
request.setBody({"Application": "Salesforce B2B","Status": "Failed " + "" + ex.getMessage()});
request.setEndpoint('https://api.example.com');
request.setMethod('POST');
HttpResponse response = http.send(request);
}
In this code snippet, we set a savepoint at the beginning of the transaction and then perform some DML operations. If a specific condition is met, we roll back to the savepoint to undo the DML changes before the introduction of the Database.releaseSavepoint, you would be unable to perform an HTTP callout after the rollback due to Salesforce's restriction on callouts after DML operations in the same transaction context. However, with the release of the releaseSavepoint method, you can release the savepoint, clearing the way for a callout to be made.
This feature increases the flexibility and power of transaction control in Apex, allowing developers to write more effective and robust error-handling and recovery processes.
As part of this feature, Database.rollback(Savepoint) and Database.setSavepoint() don’t count against the DML row limit, but still count toward the DML statement limit. This change applies to all API versions. Before Spring ’24, both the calls incremented the DML row usage limit.
When Database.releaseSavepoint() is called, SAVEPOINT_RELEASE is logged if savepoints are found and released.
For Apex tests with API version 60.0 or later, all savepoints are released when Test.startTest() and Test.stopTest() are called. A SAVEPOINT_RESET event is logged if any savepoints are reset.
Resources
Make Callouts After Rolling Back DML and Releasing Savepoints
Comments
Post a Comment