+ Start a Discussion
MikeyForceMikeyForce 

Queue up emails on exception and send together

I would like a way to queue up emails that I want to send on caught exceptions in various apex classes and triggers but I'm having a hard time figureing out how to queue them up and then know when to send them. I'd like something that in effect queues up emails and sends 5 seconds after the last email was added to the list. 

 

What is a good way of acheiving this? I've entertained several mehotds but all seem to have some kind of draw back.

 

I tried holding the emails in a list variable of a utility class but the class/variables have lost scope when the batch fires. 

 

I could insert a row into a table on each exception but I dont want to exceed SOQL/DML governer limits. 

 

It would be nice if there were some kind of class_beforeterminate event so I could send any emails before my utility class looses scope and is destroyed. 

 

Any ideas? Thanks. 

 

 

 

Damien_Damien_

Add to an error object on the execution on your batch.  If you do this correctly you won't hit limits.  Then in the finish method you can get all the emails you need to send.

MikeyForceMikeyForce

Sorry for the delay in reply.

 

Thanks for the suggestion. 

 

The errors are being logged in various recursive triggers. How would I store the errors in a variable that would be accessible from a batch, and how would I best know when to fire off that batch? I had tried setting up a scheduler  that would fire in 5 seconds, assuming that each time a trigger wanted to log an email, it could get the existing scheduler, cancel and delete it and recreate a new one to fire in 5 seconds--that way it would never fire until there were 5+ seconds of inactivity. I was able to abort the scheduler but I found no way to edit the existing or delete and create a new scheduler. 

 

Thanks,

-Mikey

Damien_Damien_

Just put the try/catch around the DML in the batch.  It will catch any errors in triggers too.  You don't need it to be around each call in the triggers unless you wanted them to be trigger specific.