Series on Exception: Ep-01

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

This will be a series of blogs on exceptions in Salesforce , this is the first one that I thought of writing about .

Why the exception occurred?

The reason being that you cannot perform a DML operation prior to callout in the same transaction, that is issue occurs when you first perform DML and then callout in the same transaction.

How to solve it ?

In one line answer : Split the transactions.

You may have to create a record and then update it with information provided by a Web Service. However, a Web Service Callout may not occur after a DML statement within the same transaction. To achieve the required action, the transaction must be separated into two parts so that the DML transaction is completed before the Web Service Callout occurs.

Here’s a demo :

insert listofOpps;

string jsonString = JSON.serializePretty(listofOpps );

callout(jsonString);

In future method make callout:

@future(callout = true)
public static void demoCallout(string jsonString){
//do callout here rest or soap
}

But what if the response needs to be returned to a lightning page ?

Answer in the upcoming blog post EP-02