0

I am trying to empty the recycleBin. Thus I need to query the existing SObjects of the records. If a match of the records SObject Name has been found, than the query should happen. Else it just shouldn't query anything. The return type is a query. How should I write the else part without having crashing problems when the SObject does not exists.

I thought of a try catch block where the try part would contain the

if(exists){query;}

and the catch part would just don't do anything, means it would be empty. Does that make sense? What would you suggest?

    Boolean exists = Schema.getGlobalDescribe().containsKey(sObjectName);
 try {
       if(exists){
          return Database.getQueryLocator('SELECT Id FROM ' + sObjectName 
          +' WHERE isDeleted=true ALL ROWS');
       }
 }
 catch (QueryException ex) {
        // do nothing
 }

1 Answers1

0

Assuming you have a method which will return the Database.getQueryLocator

public Database.QueryLocator testMethod(String sObjectName )
{
    return Database.getQueryLocator('SELECT Id FROM ' + sObjectName 
    +' WHERE isDeleted=true ALL ROWS'); 
}

Check if the sObject exists before calling the method.

Boolean exists = Schema.getGlobalDescribe().containsKey(sObjectName);
if(exists)
{
   Database.QueryLocator ql = testMethod(String sObjectName);  
}
Noor A Shuvo
  • 2,639
  • 3
  • 23
  • 48
  • That is also what I wrote above, only you have the return of a Query within a method. I am more interested in the case, what I should do, when the SObject does NOT exist? Should I catch this case? Or should I just don't put anything else, but the if clause? – staci cara May 26 '19 at 07:51
  • The problem is, that since this check happens in a start() method of a batch, the execute() will expect a query to work with. So in my eyes the batch won't be able to be executed if the SObject cannot be found. What happens if the batch cannot be executed? Would Salesforce throw an error? Or is it harmless? – staci cara May 26 '19 at 07:57
  • Additionally to that it is not possible to have a start() with the expecting return type of a Database.QueryLocator and just have an if block where the return type is within it. The method won't compile, because it is still expecting a return type! – staci cara May 26 '19 at 08:13
  • @stacicara : Can you paste your full code or a demo full code so that I can know what is the problem here. You are implementing it in Schedulable apex, right? – Noor A Shuvo May 27 '19 at 07:50