Attempting to modify a Lead Convert Trigger getting an Attempt to de-reference a null object

Salesforce Asked by Michael Canelas on December 1, 2020

We’re using what is basically the example trigger for the lead convert process. We have added a specific queue to the lead process, so if we have auto conversions that come, that have been put in the queue, it errors out. I have tried to specify an ID, or pull the current user ID that’s running the apex which is an integration user. This is my code and I’m getting " response: APEX call failed; received error message: Attempt to de-reference a null object"

I know I shouldn’t hard code a value on this, but I don’t know how to get the running user in the current class, and I’m still not sure that’s causing my error.

global with sharing class RestLeadConvert {            

    global static String doPost() {
        String result = '';
        String errorMessage = '';
            RestRequest req = RestContext.request;
            RestResponse res = RestContext.response;
            String bodyJson = req.requestBody.toString();
            Map<String, Object> requestContent = (Map<String, Object>)JSON.deserializeUntyped(bodyJson);
            String leadId = (String)requestContent.get('leadId');
            String accountId = (String)requestContent.get('accountId');
            Database.LeadConvert lc = new Database.LeadConvert();
            if (accountId != null && accountId != '') {

//Added Conditions// if (String.valueOf(lc.getOwnerId()).startsWith(’00G’)){
// lc.setOwnerId( ‘XXXXXXXXXXXXXXX’);}

            LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            Database.LeadConvertResult lcr ;
                lcr = Database.convertLead(lc);
            result = 'success';
        catch(exception ex){
            system.debug('***NOT CONVERTED**');    
            result = 'failed';
            errorMessage = ex.getMessage();       
        JSONGenerator gen = JSON.createGenerator(false);
        gen.writeStringField('result', result);
        gen.writeStringField('errorMessage', errorMessage); 
        return gen.getAsString();
        String response = '{'result': '' + result + '', 'errorMessage': '' + errorMessage + ''}';
        return response;

One Answer

The Database.LeadConvert object doesn't magically get all the values from the database. You need to actually query the record.

Lead leadRecord = [SELECT OwnerId FROM Lead WHERE Id = :leadId];
if(leadRecord.OwnerId.getSObjectType() == Group.sObjectType) {

Correct answer by sfdcfox on December 1, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP