0

i am doing an callout to a third parity using a trigger. and I am getting the error.

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY message: LeadCallout: execution of AfterInsert caused by: System.NullPointerException: Argument cannot be null. Class.System.EncodingUtil.urlEncode: line 30, column 1 Class.PostLeadtoBP.makePostLeadtoBP: line 13, column 1 Trigger.LeadCallout: line 3, column 1 errorCode: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

This is the error I got from workbench doing a test with Rest Explore post to the Lead API. here is my Trigger:

trigger LeadCallout on Lead (after insert) {
    For (Lead l: Trigger.new){
        PostLeadtoBP.makePostLeadtoBP(l.Id, l.Phone);              
    }
}

Here is the Class:

public class PostLeadtoBP {
    public static void makePostLeadtoBP(String leadId, String phoneNo){
        Http http = new Http();
        HttpRequest req = new HttpRequest();
            long unixTime = System.currentTimeMillis() / 1000L;
        HttpResponse res = new HttpResponse();
        req.setEndpoint('/clientweb/api/v1/chats?tenantUrl=sprout.brightpattern.com&timestamp='+unixTime);
        req.setMethod('POST');
        // Set Header for the Authorization
        req.setHeader('Content-Type', 'application/json;charset=UTF-8');
        req.setHeader('Authorization', '********************* appId=\"*********************\", clientId=\"WebChat\"' );
        // Set the body as a JSON object
        req.setBody(',parameters: {LeadID='+EncodingUtil.urlEncode(leadId,'UTF-8')+'phone='+EncodingUtil.urlEncode(phoneNo,'UTF-8') );
        req.setCompressed(true); // otherwise we hit a limit of 32000
         try {
            res = http.send(req);
        } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
            System.debug(res.toString());
        }
    }
}

1 Answer 1

3

This error is fairly self-explanatory. You're passing a null value to EncodingUtil.urlEncode and that's not allowed. You only call that method at one location:

req.setBody(',parameters: {LeadID='+EncodingUtil.urlEncode(leadId,'UTF-8')+'phone='+EncodingUtil.urlEncode(phoneNo,'UTF-8') );

Since this Lead's Id cannot be null in an after insert context, the phone number is your culprit.

You need to add logic to handle a null value, such as skipping this record or supplying a default, like an empty string.

However, once you fix that problem you're going to get another error, because you cannot make callouts synchronously from a trigger context. You'll need to mark that callout method @future or use another form of Asynchronous Apex to push the callouts into another transaction.

Note also that the future method limit in a transaction is 50. By adopting this architecture, you're severely constraining the number of records you can process in a transaction, and leaving the door open to limits problems very quickly.

0

You must log in to answer this question.

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