最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

salesforce - (NumberOfErrors > 0). When does the NumberOfErrors in AsyncApexJob become greater than 0, and how to write a

programmeradmin4浏览0评论

I'm writing a batch class in Apex, and I want to properly cover the scenario where AsyncApexJob.NumberOfErrors > 0.

In my batch class, I check for errors in the finish method like this:

public void finish(Database.BatchableContext BC) {
    AsyncApexJob job = [
        SELECT 
            Id
            , Status
            , NumberOfErrors
            , TotalJobItems 
        FROM AsyncApexJob 
        WHERE Id = :BC.getJobId()
    ];

    if (job.NumberOfErrors > 0) {
        System.debug('Batch failed with errors.');
        // Todo somthing
    } else {
        System.debug('Batch completed successfully.');
        // Todo somthing
    }
}

My questions:

  1. In which scenarios does AsyncApexJob.NumberOfErrors become greater than zero?
  2. How can I properly write a test class to cover this case?

From my research, NumberOfErrors increases when an unhandled exception occurs inside the execute method. However, when testing, I cannot directly control AsyncApexJob, and it seems NumberOfErrors is always 0 in tests.

Here is a simplified version of my batch class:

global class MyBatchClass implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator([SELECT Id FROM Account]); 
    }

    public void execute(Database.BatchableContext BC, List<Account> scope) {
        delete scope;
    }

    public void finish(Database.BatchableContext BC) {
        AsyncApexJob job = [
            SELECT 
                Id
                , Status
                , NumberOfErrors
                , TotalJobItems 
            FROM AsyncApexJob 
            WHERE Id = :BC.getJobId()
        ];

        if (job.NumberOfErrors > 0) {
            System.debug('Batch failed with errors.');
            // Todo somthing
        } else {
            System.debug('Batch completed successfully.');
            // Todo somthing
        }
    }
}

Thanks!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论