Catching an UnexpectedException?

My specific questions are (for the below detail):

  1. Anyone have any idea why the design is like this?
  2. Is the only solution to always clean the content perfectly before saving it?

This type is not mentioned in Exception Class and Built-In Exceptions (that does mention that governor limit LimitException can’t be caught) and this code compiles:

    try {
        // Update some ContentNote objects
    } catch (DmlException e) {
    } catch (UnexpectedException e) {

but when it runs and the update throws an UnexpectedException with the message:

Note can’t be saved because it contains HTML tags or unescaped
characters that are not allowed in a Note.

the catch of UnexpectedException doesn’t work.


System.UnexpectedException gets thrown a lot with Note inserts if you do not prepare the content exactly right, and they cannot be caught or handled in any way.

I wrote an open source package a while ago to abstract over some of these issues. From its documentation, a summary of the requirements:

The following steps are required to prepare note content for insertion into Salesforce:

  1. Replace all basic HTML characters (<>"'&) with their corresponding entities (&amp; and friends).
  2. Replace all line breaks with <br> (taking care with Windows CRLF/Linux LF/Mac CR)
  3. Replace &apos; with &#39;.
  4. Do not replace Unicode characters with entities. Other entities, including &apos;, result in an exception. Unicode should be left as the bare characters.
  5. Ensure that the source content is well-formed Unicode/UTF-8 and does not contain non-printable characters.
  6. The title must not be null, zero-length, or consist only of whitespace. The title need not be escaped.

So while I don’t have an answer to (1), the answer to (2) is “yes.”

The skeleton of the code that I worked out to avoid the issue looks like this:

public void addNote(String title, String content, Id linkedTo, String visibility, String shareType) {
    ContentNote cn = new ContentNote();

    if (title != null && title.normalizeSpace().length() > 0) {
        // A null, zero-length, or all-whitespace title will result in an UnexpectedException on insert.
        cn.Title = title;
    } else {
        cn.Title = 'Untitled Note';

    cn.Content = Blob.valueOf(content.escapeXML().replace('\r\n', '<br>').replace('\r', '<br>').replace('\n', '<br>').replace('&apos;', '&#39;'));

    insert cn;

    ContentDocumentLink cdl = new ContentDocumentLink();

    cdl.ContentDocumentId = cn.Id;
    cdl.LinkedEntityId = linkedTo;
    cdl.Visibility = visibility;
    cdl.ShareType = shareType;

    insert cdl;

Source : Link , Question Author : Keith C , Answer Author : David Reed

Leave a Comment