Inner Class Without Sharing not working as expected

apexerror-messagesinner-classsharingwithout-sharing

I found this post (Sharing rules and Inner classes), which references documentation that inner classes do not inherit the sharing of their container class.

From the documentation:

Both inner classes and outer classes can be declared as with sharing.
Inner classes do not inherit the sharing setting from their container
class. Otherwise, the sharing setting applies to all code contained in
the class, including initialization code, constructors, and methods.

This makes sense to me, and I was fine with this because I wanted to implement a separate, private inner class anyway specifically designed to bypass sharing in some situations within the service class. I thought that this would be more elegant than creating a separate, dedicated without sharing class.

However, in my testing, I'm finding that the end user is still receiving an INVALID_CROSS_REFERENCE_KEY, invalid cross reference id error when running new WithoutSharing().updateObjRecords(list) when they only have read-only access to the objects in question.

The below code is an example of the scenario I'm trying to implement, but sharing seems to still be applied. Am I missing something here? Should this be possible, or am I going to have to create a separate Service class specifically designed as without sharing?

public with sharing class ObjectAService {
  public static void updateDaysSinceLastCalled(
    List<OBJ_A__c> objList,
    Map<String, DateTime> recordMap
  ) {
    // Do Logic (Removed for Brevity)

    if (!list.isEmpty()) {
      new WithoutSharing().updateObjRecords(list);
    }
  }

  private without sharing class WithoutSharing {
    public void updateObjRecords(
      List<OBJ_A__c> lstRecordsToUpdate
    ) {
      update lstRecordsToUpdate;
    }
  }
}

Best Answer

After much debugging, this issue actually ended up being completely unrelated to the code and was instead a Sandbox data issue. Some of the required lookup fields had values populated which didn't exist anymore, resulting in the error.

Related Topic