What would be a better way of error handling in batch apex other than using a n object to insert errors. Can we send error messages to the user in an email from finish method.

Currently, I'm doing something like this.

            Counter += ListtoInsert.size();
        }Catch(exception e){
            system.debug('Exception Caught:'+e.getmessage());

But I'm just debugging them. How can i send error messages to the user.

Or is there any better approach in addressing the issue.

  • 2
    You can send the errors in a email from the finish method. Just create a variable to gather them from your batch execute method, then format your mail and send it out in the finish method. Mar 10, 2016 at 20:55
  • @JesseMilburn You probably should have added that as an answer-- that's basically what I said.
    – sfdcfox
    Mar 10, 2016 at 21:03

1 Answer 1


Yes, you can certainly send an email to the user; in fact, this is my preferred method to avoid spamming users. You can do this by way of the Database.Stateful.

public class MyBatchable implements Database.Batchable<SObject>, Database.Stateful {
    Exception[] errors = new Exception[0];
    public Iterable<SObject> start(...) {
    public void execute(...) {
        try {
        } catch(Exception e) {
    public void finish(...) {
        if(!errors.isEmpty()) {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setSubject('Errors occurred during batch process.');
            Messaging.sendEmail(new Messaging.Email[] { mail });

You might also include a way to send emails if too many errors have stacked up, or limit yourself to some number of exceptions (say, the first 50 or 100). Keep in mind that you do have a limited amount of memory available, so if you're concerned about having a large number of errors, consider logging them to the database and then querying them back in your finish method.

  • I've found I need to add a try/catch around the Messaging.sendEmail in this scenario as often with packages and sandboxes etc... the user running the batch can't send an outbound email. Just something to watch out for is the batch might otherwise work and then fall over in the finish method. Mar 10, 2016 at 23:15

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.