Skip to content

Log Apex/flow Exception Errors in a custom object Salesforce

Logging errors are helpful, primarily when an error occurs in the future, background apex jobs, or flows. Especially when you want to investigate why some background jobs are not working as expected and you want to know how frequently the jobs are failing.

Using the following solutions you can find the apex error exceptions easily. You can see why the error occurred and on which line of code the error occurred. You can see the errors in a list view and can do reporting on a specific error.

STEP 1

Create a custom object named Error Log with the following fields. And also create a tab for this object.

Field NameTypeDescription
NameStandard Auto NumberDisplay Format ERR-{000000}
Class NameText (255)Class name where the error occurred
Function NameText (255)Function name where the error occurred
Error MessageLong Text Area(131072)Detailed error message
Stack TraceLong Text Area(32768)Information about the error message
Record IdText(255) (External ID)The record Id for which the error occurred
Line NumberNumber(18, 0)The line number where the error occurred
Error Log Custom Object

STEP 2

Create an apex class that takes error information and returns an instance of the custom object with the fields populated.

public without sharing class ErrorLog {

    public static Error_Log__c logError(String ClassName, String FunctionName, String ErrorMessage, String StackTrace, Integer LineNumber, String recordId) {

        Error_Log__c logger = new Error_Log__c();
        logger.Class_Name__c = className;
        logger.Function_Name__c = FunctionName;
        logger.Error_Message__c = ErrorMessage;
        logger.StackTrace__c = StackTrace;
        logger.Line_Number__c = LineNumber;
        logger.Record_Id__c = recordId;
        return logger;
    }
}

STEP 3

Update your apex classes and implement error logging as shown in the following example apex class. This class contains a future method that logs error messages when an unhandled exception occurs or the API request fails with an error code other than 200 or 201.

public class MyApexClass {

    @future(callout = true)
    public static void myfuturemethod(String recordId) {

        try {
            list < Error_Log__c > ErrogLogs = new list < Error_Log__c > ();

            if (String.isBlank(RecordId)) {
                ErrogLogs.add(ErrorLog.logError('MyApexClass', 'myfuturemethod', 'Some error message', 'Record Id is blank', 10, RecordId));
            }
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            req.setEndpoint(endpoint);
            req.setMethod(method);
            req.setHeader('Content-Type', 'application/json');
            req.setTimeout(120000);

            req.setHeader('Accept', 'application/json');
            system.debug('body::' + JSONBody);
            req.setBody(JSONBody);

            HttpResponse res = new HttpResponse();
            res = h.send(req);
            if (res.getStatusCode() != 200 && res.getStatusCode() != 201) {
                ErrogLogs.add(ErrorLog.logError('MyApexClass', 'myfuturemethod', res.getBody(), 'Error making api request.', 26, RecordId));

            }
            if (ErrogLogs.size() > 0)
                insert ErrogLogs;


        } catch (Exception ex) {
            Error_Log__c errLog = ErrorLog.logError('MyApexClass', 'myfuturemethod', ex.getMessage(), ex.getStackTraceString(), ex.getLineNumber(), RecordId);
            insert errLog;
        }
    }
}

Boom! You are done.

Additionally, you can create a platform event object in Salesforce with the same fields. And then can simply publish platform event records from either apex code or using fault path/connector in the flow. Then create a platform event subscription record trigger flow to create a record in the custom object mapping the correct fields.

2 Comments

  1. Rohit Rohit

    The future method must be declared as static in your code have some error please check and correct it.

    • Thanks, Rohit. I have updated the code.

Comments are closed.