You have uncommitted work pending Salesforce Exception

You have uncommitted work pending Salesforce Exception

Exception:

System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

Callouts are not allowed when there is an uncommitted transaction pending. For example, if a save point is set before a DML operation, a callout cannot be made based on the results of that operation to commit or roll back the save point. You cannot perform a DML operation prior to a callout. All the DML operations should be invoked only after you are done with callouts. So, make a webservice callout first and then save the request.

Sample Code to reproduce the issue:

insert new Case(
    Status = 'Working',
    Subject = 'Testing',
    Description = 'Example'
);
String endpoint = 'https://api.status.salesforce.com/v1/instances/NA100/status';
HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setEndPoint( endpoint );
req.setMethod( 'GET');
HTTPResponse res = h.send( req );

In the above code DML is done before the Callout. To resolve the issue, the DML should happen after the Callout.

String endpoint = 'https://api.status.salesforce.com/v1/instances/NA100/status';
HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setEndPoint( endpoint );
req.setMethod( 'GET');
HTTPResponse res = h.send( req );
insert new Case(
    Status = 'Working',
    Subject = 'Testing',
    Description = 'Example'
);

Leave a Reply