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

Using Try Catch with If Then Statements

Having a lot of trouble with test method for this. Class works find using If...Else statement but I cannot catch the error on the Else side.  Killing me.


Class for Trigger

for(Identifier__c iden : identifiers) {
if(iden.Type__c == 'Email'){
if( PatternEmail.matcher(iden.Master_Contact_ID__c).matches()){
iden.Email__c = iden.Master_Contact_ID__c;
} else

iden.Master_Contact_ID__c.addError('Please check the format of the email you entered.');


Above works fine, but when I write the test class I'm getting "SObject row does not allow errors"


I guess I'm not sure where the try...catch block should go to catch above?  Test class or in code above?  How?




Test class. Your trigger is just providing your user with an error because the data is invalid. Within your test class is where you should get the error back and verify it.


Lastly, is Master_Contact_ID__c a formula which you are pulling an email / text value from? You can't throw errors on formula fields, try putting it on the object itself of the email field.


Kind of what I thought so I'll play with it a litle more.  No, the Master__Contact field isn't a formula. The UI is working as expected with user gettting an error, it's just catching it for the bulk processing that isn't working.  Logs are validating that there was an error, but the test isn't catching it correctly I guess.


Database.SaveResult Documentation


What I suggest is then, on your test case use the following example:


List<Identifier__c> records = new List<Identifier__c>();

for(Database.SaveResult record :Database.Insert(records, false)){ if(!record.isSuccess()) system.debug('\n\n\nError Thrown!\n' + record.getErrors()[0].getMessage() + '\n\n\n'); }


Please update this example to fit your needs on validating your logic for your test case.




Thanks much for the suggestion.  I'm going to have to come back to that one though as it will mean I need to change the Trigger to use the Database method.  That might be answer, but I screwed up the trigger, which works fine, earlier trying to get this so don't want to do that again.


I'll see if can play with that part of it this weekend.  I left out the bulk fail test for now which is only one that's not working.  I'll respond here when I try the Database method.




Well the example i was providing was for your testcase, but if it makes your trigger better, go for it. Glad I could help.