function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
TaruniTaruni 

Exception handling

Hi,

 

We have a Batch class which is scheduled to run every day. This batch will update a specific user with role to a custom field on Oppty.

The problem is that we have a Validation rule on Oppty, because of which some Batches are failing.

I want to bypass this validation rule while the Batch job is running.

 

Is the below code snippet correct?

 

*************************************************************************************************************************************

 try{    
      update opp; //This is the Oppty which we are updating
      }
     
      Catch(Exception e)
      {
         string sErrMsg=e.getmessage();
       if(sErrMsg.contains('Opportunities can only be created for active Prospects/Customers.You are unable to create this opportunity because either your prospect has not been approved yet or Prospect/Customer record is inactive--which will require onboarding the Prospect/Customer.'))
           return;
      }

 

*************************************************************************************************************************************

will this piece of code bypass the validation rule and will this help the batches to run successfully?

Best Answer chosen by Admin (Salesforce Developers) 
harsha__charsha__c

Instead, you can impose the validation rule conditions on the opportunities before updating them. And the opportunities fail to meet the validation rule can be skipped from updating.

 

This will avoid the erroronious opportunities not to be updated. 

 

However,  the validation rules can not be compromised, so we better check them before we perform updation on the records.

All Answers

harsha__charsha__c

Instead, you can impose the validation rule conditions on the opportunities before updating them. And the opportunities fail to meet the validation rule can be skipped from updating.

 

This will avoid the erroronious opportunities not to be updated. 

 

However,  the validation rules can not be compromised, so we better check them before we perform updation on the records.

This was selected as the best answer
ysrysr

Hi Taruni,

 

Try and Catch blocks are intended for tracking the exceptions, the peice of code whihc you have mentioned in Catch block will not bypass the validation rule.

 

Not only in this scenario, you can't by pass the validation rules while executing the DML in apex.

 

soultion is you have to bypass the validation rule level.

 

Thanks