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
Sudeep SinghSudeep Singh 

How to get exception and success message

I have a  batch class which is running everyday and checks if the contract status is Activated or not if activated then it creates the order and its products.

1. Get the everyday logs on batch runs and number of order created and its status.

2. In case batch did not run due to any issue(exceptions)  that also needs to be notified.

Can I get any help how to achieve on this.

Thanks
Best Answer chosen by Sudeep Singh
Prateek Prasoon 25Prateek Prasoon 25

Yes, I can help you with that. Here are a few ways to achieve this:

Get the everyday logs on batch runs and number of orders created and their status:
You can create a custom object to store the batch run information, such as the date, number of orders created, and their status.
In your batch class, after each run, you can create a record in this custom object and store the relevant information.
You can then use Salesforce reporting or dashboards to get an overview of the batch runs and orders.
Notify in case batch did not run due to exceptions:
You can use the try-catch block in your batch class to catch any exceptions that occur during the run.
In the catch block, you can send an email notification to the relevant parties using the Messaging.SingleEmailMessage class in Salesforce.
You can also use a platform event in Salesforce to capture the exceptions and trigger a process or flow to send the notifications.
Note: To use the Messaging.SingleEmailMessage class, you need to have the proper email sending permissions in Salesforce.

global class OrderBatch implements Database.Batchable<sObject>, Database.Stateful {
 
    global final String query;
    global Integer orderCount;
    global String batchRunStatus;
 
    global OrderBatch(String query) {
        this.query = query;
        this.orderCount = 0;
        this.batchRunStatus = 'Success';
    }
 
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext bc, List<sObject> scope) {
        List<Order> orders = new List<Order>();
        List<OrderItem> orderItems = new List<OrderItem>();
 
        try {
            for (sObject s : scope) {
                Contract contract = (Contract)s;
                if (contract.Status == 'Activated') {
                    Order order = new Order(
                        AccountId = contract.AccountId,
                        ContractId = contract.Id,
                        EffectiveDate = contract.StartDate,
                        Status = 'Draft'
                    );
                    orders.add(order);
 
                    for (ContractLineItem cli : contract.ContractLineItems) {
                        OrderItem orderItem = new OrderItem(
                            OrderId = order.Id,
                            PricebookEntryId = cli.PricebookEntryId,
                            Quantity = cli.Quantity,
                            UnitPrice = cli.UnitPrice
                        );
                        orderItems.add(orderItem);
                    }
                }
            }
 
            insert orders;
            insert orderItems;
            orderCount = orders.size();
        } catch (Exception e) {
            batchRunStatus = 'Failed';
            sendNotificationEmail(e);
        }
    }
 
    global void finish(Database.BatchableContext bc) {
        BatchRun__c batchRun = new BatchRun__c(
            Date__c = Date.today(),
            OrderCount__c = orderCount,
            Status__c = batchRunStatus
        );
        insert batchRun;
    }
 
    private void sendNotificationEmail(Exception e) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'admin@example.com'});
        email.setSubject('Order Batch Failed');
        email.setPlainTextBody('The Order Batch has failed with the following error: ' + e.getMessage());
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}

You can schedule this batch class to run daily using the Salesforce Scheduled Apex feature.
This example shows how to catch exceptions that occur during the batch run and send a notification email to the admin. The batch run information (date, order count, and status) is stored in a custom object named "BatchRun__c".
Note: This is just a sample code and may need to be adapted to fit your specific requirements and use case.

If you find my answer helpful, please mark my answer as the best answer.

All Answers

Prateek Prasoon 25Prateek Prasoon 25

Yes, I can help you with that. Here are a few ways to achieve this:

Get the everyday logs on batch runs and number of orders created and their status:
You can create a custom object to store the batch run information, such as the date, number of orders created, and their status.
In your batch class, after each run, you can create a record in this custom object and store the relevant information.
You can then use Salesforce reporting or dashboards to get an overview of the batch runs and orders.
Notify in case batch did not run due to exceptions:
You can use the try-catch block in your batch class to catch any exceptions that occur during the run.
In the catch block, you can send an email notification to the relevant parties using the Messaging.SingleEmailMessage class in Salesforce.
You can also use a platform event in Salesforce to capture the exceptions and trigger a process or flow to send the notifications.
Note: To use the Messaging.SingleEmailMessage class, you need to have the proper email sending permissions in Salesforce.

global class OrderBatch implements Database.Batchable<sObject>, Database.Stateful {
 
    global final String query;
    global Integer orderCount;
    global String batchRunStatus;
 
    global OrderBatch(String query) {
        this.query = query;
        this.orderCount = 0;
        this.batchRunStatus = 'Success';
    }
 
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext bc, List<sObject> scope) {
        List<Order> orders = new List<Order>();
        List<OrderItem> orderItems = new List<OrderItem>();
 
        try {
            for (sObject s : scope) {
                Contract contract = (Contract)s;
                if (contract.Status == 'Activated') {
                    Order order = new Order(
                        AccountId = contract.AccountId,
                        ContractId = contract.Id,
                        EffectiveDate = contract.StartDate,
                        Status = 'Draft'
                    );
                    orders.add(order);
 
                    for (ContractLineItem cli : contract.ContractLineItems) {
                        OrderItem orderItem = new OrderItem(
                            OrderId = order.Id,
                            PricebookEntryId = cli.PricebookEntryId,
                            Quantity = cli.Quantity,
                            UnitPrice = cli.UnitPrice
                        );
                        orderItems.add(orderItem);
                    }
                }
            }
 
            insert orders;
            insert orderItems;
            orderCount = orders.size();
        } catch (Exception e) {
            batchRunStatus = 'Failed';
            sendNotificationEmail(e);
        }
    }
 
    global void finish(Database.BatchableContext bc) {
        BatchRun__c batchRun = new BatchRun__c(
            Date__c = Date.today(),
            OrderCount__c = orderCount,
            Status__c = batchRunStatus
        );
        insert batchRun;
    }
 
    private void sendNotificationEmail(Exception e) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'admin@example.com'});
        email.setSubject('Order Batch Failed');
        email.setPlainTextBody('The Order Batch has failed with the following error: ' + e.getMessage());
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}

You can schedule this batch class to run daily using the Salesforce Scheduled Apex feature.
This example shows how to catch exceptions that occur during the batch run and send a notification email to the admin. The batch run information (date, order count, and status) is stored in a custom object named "BatchRun__c".
Note: This is just a sample code and may need to be adapted to fit your specific requirements and use case.

If you find my answer helpful, please mark my answer as the best answer.
This was selected as the best answer
Sudeep SinghSudeep Singh

I dont need to send any email. I just want to store the information that which contract failed to create order and order products. If it is succeed then how many records are getting processed. Those all details need to store.

Thanks

por gelpor gel
The great features of epayitonline are that you don't have to provide any personal information or create an account to pay health bills online. https://peryourhealth.ninja/features-of-epayitonline/