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
dinesh sivalingam 10dinesh sivalingam 10 

future method error handling

Hi

How to send an exception email if the Future method fails, i have tried this in catch block but it throw mixed DML exception.

Inside the future method within the try block am trying to create a User record, if any error occurs in User record creation then the DML exception is catched in the catch block, in that case i need to send an email to system admin about the error in user account creation.

please let me know your ideas to implement this

Thanks
SandhyaSandhya (Salesforce Developers) 
Hi Dinesh Sivalingam,

Below is the sample code for the same.
 
try{
     update account;
} catch (DMLException e){
     ApexPages.addMessages(e);

     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
     String[] toAddresses = new String[] {'developer@acme.com'};
     mail.setToAddresses(toAddresses);
     mail.setReplyTo('developer@acme.com');
     mail.setSenderDisplayName('Apex error message');
     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
     mail.setPlainTextBody(e.getMessage());
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}

Please refer below link for the similar discussion.

https://developer.salesforce.com/page/An_Introduction_to_Exception_Handling

http://salesforce.stackexchange.com/questions/13730/email-not-sent-from-within-catch-or-finally-when-exception-is-rethrown-why
 
Hope this helps you!

Please mark it as Best Answer if my reply was helpful. It will make it available for other as the proper solution.
 
Thanks and Regards
Sandhya



 
dinesh sivalingam 10dinesh sivalingam 10
I have tried the above code but still getting the same MixedDML exception error
Error Message for Reference:
First error: SendEmail failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): EmailMessage, original object: User: []
SandhyaSandhya (Salesforce Developers) 
Hi,

Please refer below link why this error will be populated.

https://developer.salesforce.com/forums/?id=906F00000008wAZIAY
 
Thanks and Regards
Sandhya