2

Good day everyone,

At the moment, I've created a batch process wherein its purpose is to parse csv file and save the parse data to salesforce object. During the batch process I have to check the data if it is in correct format(or the data is correct). Now, what I want is that when there is some error found in the data during the process, I want to list those errors and then after that I will send it to the uploader. At the moment I used try and catch to list all the errors. My problem is that how I will get those data in finish() method of the batch class. Please help.

Thank you !!!

2

Providing you add the marker interface Database.Stateful (see the "Using State in Batch Apex" section of Using Batch Apex) member variables are preserved between batches and through to the finish method.

So the simplest form would be:

public class MyBatchable implements Database.Batchable<SObject>, Database.Stateful {

    public String[] errors = new String[] {};

    ...

    public void execute(Database.BatchableContext bc, List<SObject> sobs) {
        for (SObject sob : sobs) :
            try {
                ...
            } catch (Exception e) {
                errors.add(e.getMessage());
            }
        }
    }

    public void finish(Database.BatchableContext bc) {
        // Do something with the errors
    }
}

Instead of just the message string, you could create your own inner class to hold other relevant information.

Not that governor limit exceptions can't be caught and so will not be handled by this code. But it is possible to query the AsyncApexJob object in the finish method using the job ID from the Database.BatchableContext to detect those; the error information is in the ExtendedStatus field.

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.