4

I have created a validation rule on Account: enter image description here

Then i have written following trigger and its helper:

trigger updateAccount on Opportunity (before insert,before update) {

     set<String> accId = new Set<String>();
     For(Opportunity record: trigger.new){
         accId.add(record.accountid);
     }
     if(accId.size() > 0){
         updateAccountHelper.updateAccount(accId);
     }
}


public class updateAccountHelper{    
    public static void updateAccount(Set<String> accIds){
        try{
            List<Account> accList = [Select Id,name from Account where id in:accIds];
            For(Account record:accList){
                record.name = 'Updated';
            }
            update accList;
        }catch(Exception e){
            system.debug('####'+e.getMessage());
        }
    }
}

My this code does not catch FIELD_CUSTOM_VALIDATION_EXCEPTION. Do anybody have any idea regarding this issue?

4

Add below 3 lines in your catch block. This will capture your validation rule exception in a more simpler form rather than providing a huge error line.

catch(exception e) 
        {
            String S1 = e.getMessage();
            S1 = S1.substringBetween('FIELD_CUSTOM_VALIDATION_EXCEPTION, ' , ': [');
            Trigger.New[0].adderror(S1);
        }

Hope this helps.

Regards! Ruchi

1

I had encountered the same thing. A try/catch block around an update statement was not catching an exception when a validation rule is violated, but I haven't been able to repeat the problem since first encountering it.

Using the following Database method call will capture the error in a SaveResult instance:

Database.SaveResult myResult = Database.update(myAccount, false);

This seems to work when passing "false" as the allOrNone Boolean argument, but not when passing "true".

A JSON string of the SaveResult would appear something like this when the rule is violated:

{ "success" : false, "errors" : [ { "statusCode" : "FIELD_CUSTOM_VALIDATION_EXCEPTION", "message" : "Phone is missing", "fields" : [ "Phone" ] } ] }

You would need to evaluate the SaveResult and apply the appropriate logic based on the "success" property. The SaveResult class also provides some methods to obtain the success value, the Id of the record, and the list of Database.Error instances.

Comparison of DML vs. Database methods

0

Try adding the "Phone" field to the query once . Might be situation that before firing the validation rule , it might be firing some other exception . Can you post the debug message in the catch block you got ?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.