I've got a managed package which needs to start a batch process from a trigger. In order to deal with subscriber orgs who are also using asynchronous apex, my code tries to start it, then uses a "run later" flag if it cannot i.e.

try {
    NebulaApiWorker.startBatch(namespace, thisSentinel.Worker_Thread__c);
    thisSentinel.Last_Run__c = Datetime.now();
} catch(AsyncException e) {
    // This can happen if we're running inside a batch or future method, 
    // just set the thread to try again later
    thisSentinel.Run_Worker_Later__c = true;
    thisSentinel.Run_Worker__c = false;

This is then picked up later by a scheduled process that runs regularly to start the batch from a context where it can work. The scheduled process is started from the InstallHandler like this:

public without sharing class NebulaApiInstallHandler implements InstallHandler, UninstallHandler {

    public void onInstall(InstallContext context) {

    public void onUninstall(UninstallContext context) {

So, the tricky thing is that the scheduled process is running as the special ghost user from the package (see InstallHandler runs under a special ghost user. What rights does it have?). When my batch runs, it causes a subscriber org trigger to run. And that subscriber trigger is failing (only as the ghost user) because their trigger ends up in a without sharing class that accesses LeadStatus:

LeadStatus convertStatus = [ Select MasterLabel From LeadStatus Where IsConverted = true limit 1];

This causes my batch to break with:

System.QueryException: sObject type 'LeadStatus' is not supported.

I can ask the subscriber to work around this in their code, but it's not something I'd like to deal with every single time. So, is there any way I can solve it from the package?

  • 2
    Maybe instead of asking the subscriber to work around it in their code, just ask them to schedule the process as their admin user instead of the ghost user? – Charles T Jul 16 '18 at 12:19
  • That is a fair point, probably should have mentioned it in the question. It would certainly work. It raises the risk that they forget to do it, but could be an option, and could be something you could put in the FAQ. – Aidan Jul 16 '18 at 12:22
  • Right, it may only be relevant for customers with their own interfering triggers. Actually, even better, you could include a "Fix Scheduled Process" button on a setup page. Document to customers that if they get certain error messages, the admin can fix it by going to that page and clicking that button. – Charles T Jul 16 '18 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.