0

We want to insert an error log record in the org whenever we receive any error in trigger execution but we want to do it by using platform event. We have tried to insert a record but were not able to do that. The code is executed fine but the record is not created or inserted.

The platform event is getting processed but not published. platform event manage Code is attached below :-

CalloutError__e errorEvent = new CalloutError__e(
        Description__c = Description,
        Error_Stack_Line__c = Error_Stack_Line,
        Error_Type__c = Error_Type
    ); 
    Error_Log__c errlog1 = new Error_Log__c();
    errlog1.Description__c = Description;
    errlog1.Error_Stack_Line__c = Error_Stack_Line;
    errlog1.Error_Type__c = 'Other';
    System.debug('errlog1 '+errlog1);
    insert errlog1;
    System.debug('errlog1'+errlog1.Id);
    //Database.SaveResult result1 = EventBus.publish(errlog1);
    
    Database.SaveResult result = EventBus.publish(errorEvent);

And called this function from the trigger catch block

CalloutError__e errlog = new CalloutError__e();
    errlog.Description__c = 'Task trigger exception - '+e.getCause() +' \n'+ e.getMessage();
    errlog.Error_Stack_Line__c = e.getStackTraceString();
    errlog.Error_Type__c = 'Other';
    errlist.add(errlog);
    CalloutErrorService errorService = new CalloutErrorService();
    errorService.handleCalloutErrorEvent(errlist);
    errorService.persistError( errlog.Description__c,errlog.Error_Stack_Line__c,errlog.Error_Type__c);
    

Please help us to solve this issue.

1 Answer 1

1

To achieve error logging through platform events. You need below things -

  1. Platform Event - with Behavior as "Publish Immediately" Trigger
  2. Handling platform event and performing DML for log record.
  3. Consumer, to do the publishing the error.

Example -

Consumer Code -

public class Calculator { 
    public static Integer division(Integer numerator, Integer denominator) { 
         try {
             return numerator/denominator;
         } catch(Exception e) {
            CalloutError__e errorEvent = new CalloutError__e(
                Description__c = 'Calculator.division',
                Error_Stack_Line__c = e.getStackTrace(),
                Error_Type__c = 'Warning'
            );
            EventBus.publish(errorEvent);
         }
         return null;
    }
}

Then the trigger of Platform Event would be like below -

trigger LogErrorTrigger on CalloutError__e (after insert) {
    List<Error_Log__c> errors = LogErrorService.generateLogRecords(trigger.new);
    insert errors;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .