Print this page

Getting notified when something goes wrong with a scheduled job

Knowledge Article Number 000232862
Description We have multiple Apex jobs running, both from Schedulable and Batchable code. While an attentive could be to examine the Apex Jobs list to check that everything is OK, it seems a better idea to have explicit notification of errors (and more detailed error information).

You can create custom object to store error information whenever the job throws error and set up workflow rule on this object to send email alerts if there is an error.

For example:
Error Log custom object with just one custom field, Trace__c, although you could break it out into different, more specific fields if you like.

So in apex class that you schedule, create a new Error Log object in catch statements to record specific error information when the job fails.

    //Some DML statement
} catch (Exception e) {         
    Error_Log__c log = new Error_Log__c();
    log.trace__c = 'Type: ' + e.getTypeName() + '\n' + 'Cause: ' + e.getCause() + '\n' + 'Message: ' 
    + e.getMessage() + '\n' + 'Line #: ' + e.getLineNumber() + '\n' + e.getStackTraceString() + '\n'
    + 'Some Custom Variable Information From Class: ' + myClassVariable;
    insert log;         

Then you can set up a workflow on the error log object to send email whenever a new error log is created. As you can see you can add different information based on what class you are using it in, its fairly flexible.

The one drawback would be that you are using a custom object for this and storing the error data, so you might want to monitor this object and periodically delete old error logs. You can have a batch class that runs monthly and deletes anything over 30 days old.

The advantage to this method is you only get alerted when there are issues. If you have a lot of scheduled classes, you can also send an email on the job completion, but with so many classes, some running every night, you don't really need to get an email just to tell you it worked fine. This will only email you when something goes wrong.

promote demote