3

I have a batch job that tries to handle any DML exceptions and write them to a separate Custom object called Feed_Log__c.

I have sometimes getting a Null pointer exception after trying to handle a UNABLE_TO_LOCK_ROW exception. Here is my catch block:

catch(DmlException e){
    feedLogToInsert.Status__c = 'Aborted';
    feedLogToInsert.Status_Message__c = 'Project-DmlException';

     for (Integer i = 0; i < e.getNumDml(); i++) {
        feedLogToInsert.Error_Count__c++;

         if(feedLogToInsert.Exception_Message__c == ''){
           feedLogToInsert.Exception_Message__c = e.getDmlId(i) + '-' + e.getDmlMessage(i);
          }
        else{
             // Check to see if we will overrun our TextArea.. only copy if not 
             // Also, added Id of offending record

             Integer insertLen = e.getDmlMessage(i).length() + 18;

             if ((feedLogToInsert.Exception_Message__c.length() + insertLen) < 32768) {
               feedLogToInsert.Exception_Message__c += ', ' + e.getDmlId(i) + '-' + e.getDmlMessage(i);
                } else {
                 System.debug(LoggingLevel.ERROR,'(BatchCarlProject) DML err: ' + e.getDmlId(i) + '-' + e.getDmlMessage(i));
                }
              }
           }
    Database.rollback(sp);
    }

I looked at the DML Exception class, and cannot see any reason why I would get a Null pointer exception as I iterate over all of the e.getNumDml() entries.

If anyone can shed light on this, I would appreciate it...

Oh, and apologies for the hard-coded 32768, but I could not find any way to find the size of the text area, such as the "C" language "sizeof" offers.

2 Answers 2

2

Do you set a value for feedLogToInsert.Exception_Message__c before your if statement? If you do not, the default value is null, not empty string. If I look at this:

String theString;
System.debug(theString == '');
System.debug(theString == null);

The first result is false, the second is true. Therefore if you try to do a += to that value, it will give you a null pointer exception.

1
  • I think that is the issue. I can see in the other part of the code, where the Feed_Log is created, it initializes the "Status_Message__c" field to ''. I suspect that is the issue. I need to make sure that the Exception_Message__c is also initialized the same way. Thanks for your suggestion!
    – mitchmcc
    Mar 29, 2015 at 15:45
3

one possible place for this error is where you apply the length() method on the error messages [ both Exception_Message__c and getDmlMessage ] ..

if there is no error message or if its null instead of empty string then you can get this error..

but if you look into the stack trace you should see the line number for the origin of this error which might give you the clue..

you can also try using String.isBlank method to check for null or empty string before applying the length function.

You must log in to answer this question.

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