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
meerameera 

Adderror + email notification

Hi Experts,

I have a requirement in which when I am creating a new record, I will do one validation in trigger and if the validation failed, I need to add error and fail that record. And I need to send an email to the account owner informing about the error. But when I tried when the add error is getting executed, email notification is not send. Is there any way that we can execute both?

Thanks
Meera
rohitsfdcrohitsfdc
Hello Meera,
Would you like to share your code?

Thanks
Rohit
meerameera
Hi Rohit,

I tried many methods like first send an email then add error, then in finally block. Please find below the last one I tried. In the debug log we can see the email is sent, but i think it is getting rolled back.

trigger beforInsertAccountTrigger on Account (before insert) {
   
   
    try{
        for(Account acc : Trigger.new){
        if(acc.name.contains('error')){
       
           
             acc.addError('This is not a valid name');
        }
    }
    }catch(Exception e){
System.debug(e.getErrorMessage());
    }finally{
        Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
       String[] toAddresses = new String[] {'user@domain.com'};
       mail.setToAddresses(toAddresses);  
       mail.setSenderDisplayName('Apex error message');
       mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
       mail.setPlainTextBody('Testing for email notification');
       Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
   
   
}

Thanks
Meera
rohitsfdcrohitsfdc
Meera,
adderror is not an exception. Hence it will never execute finally block.  Use it like this instead.

if(acc.name.contains('error')){
       
           
             acc.addError('This is not a valid name');
sendemail();
 }

public void sendemail(){
// paste your sendemail code here.
}

Hope this helps you..

meerameera
Hi Rohit,


I tried this first, but email is not getting trigered.

Thanks
Meera
rohitsfdcrohitsfdc
Check your email log files in Setup->monitoring.

If that doesnt help, send me the debug log, i will take a look at it
Chris SweetChris Sweet
Shot in the dark since this is 3 years later, but any chance you were able to do this? I would like to do this exact thing (block insert, send email).