+ Start a Discussion

Max length error on Case Comment after using Left() to shorten

I have a customer email handler class that takes email messages and does some actions.  One of the things it does is create a comment on the appropriate case with the body of the email included.

The comment that it creates contains some language pertaining to the email, when it was received, the source, and a list of any attachments included.  I have set the piece the code up to automatically reduce the length of the comment to fall well within the 4000 character limit, but for some reason the code is still throwing errors when emails are received that are too long.

Here is a snippet of the code:
        string commentBody;       
        commentBody += 'Email Subject:  ' + email.subject + ' \r\n';    
        commentBody +=  ' \r\n';
        commentBody +=  'Email Body:  ' + ' \r\n';
        if(email.plainTextBody.length() > 3500){
         commentBody = commentBody + email.plainTextBody.trim().left(3500)+ '\r\n' + '\r\n' + '**NOTE: EMAIL BODY TRUNCATED IN COMMENT. SEE EMAIL ATTACHED TO CASE FOR FULL TEXT**';         
         commentBody += email.plainTextBody.trim();
        if(fileAttachmentNames.size() > 0){
            string attachmentsText;
            attachmentsText += ' \r\n';
            attachmentsText += ' \r\n';
            attachmentsText += 'Attachments received:  ';           
            For(String faName :fileAttachmentNames){
                attachmentsText += ' \r\n';
                attachmentsText += faName;
            commentBody = commentBody.left(3500 - attachmentsText.length());
            commentBody += attachmentsText;
        newComment.CommentBody = commentBody.trim();
        insert newComment;

However, as I am using the left() method to reduce the length of the comment to 3500 characters I am still getting this error when the email is too long:
"System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Body: data value too large:"  The error is being thrown on the INSERT line, not before so it is acting like the comment body is too long or something.  Is it possible that the left() method is ignoring HTML values in the string or something?  What other methods should I use to help make sure that the comment stays within the 4000 character limit?


Jeremy Stender

Eli Flores, SFDC DevEli Flores, SFDC Dev
Hi Jeremy,

The commentBody can be 4k bytes. That doesn't necessarily mean 4k. If you are getting foreign characters, chances are those are consuming 2 bytes per char.  I'm not sure if there are string methods that work on a strictly byte basis. They've added heaps of string methods in the last two releases, you may want to peruse those to see if you can work intelligently near the limit.

In lieu of that, you may have to adjust .length() checks against a 2k char limit to account for cases where you receive unicode.