Error log capture in Salesforce

The purpose of the error log framework is to keep track of records or system failures so that the system administrator can resolve to enhance the data loss and enhance the system process.

For any apex failure, the error logs were maintained through this custom solution. To build an error log framework, it is necessary to know the basics of exception handling in Apex.

  1. Create a custom object
  2. Create the Apex class
  3. Sample Trigger

Create a Custom Object

Object Name: Error

API Name: Error__c

Fields:

Field LabelField NameData Type
Class NameClass_Name__cText(100)
DescriptionDescription__cLong Text Area(32768)
Error NameNameAuto Number
Method NameMethod_Name__cText(100)
Object NameObject_Name__cText(18)
Stack TraceStack_Trace__cText(255)
TypeType__cText(100)
User IdUser_Id__cText(20)

Create the Apex Class

public class CustomHandleException extends Exception 
{
    public static void LogExceptionMethod(Exception e,string objname)
    {
        try
        {
            Error__c err = new Error__c();
            err.Description__c = e.getMessage();
            err.Stack_Trace__c = e.getStackTraceString();
            err.Type__c = e.getTypeName();
            err.Class_Name__c = 'CustomHandleException';
            err.Method_Name__c = 'LogExceptionMethod';
            err.User_Id__c = UserInfo.getUserId();
            err.Object_Name__c = objname;            
            insert err;          
            
        } finally{
            
        }            
    }
}

Sample Trigger

This trigger has been intentionally written to through error so as to log the error

trigger ErrorAccountTrigger on Account (After insert) {
    
    string objName;    
    list <contact> CntLst = new list <Contact> ();
    List<Account> accnew = Trigger.New;
    
    try{
        List<Account> accnew = Trigger.New;
        for(Account accItems: accnew){
            
            Contact newContact = new Contact();            
            newContact.AccountId = accItems.Id;            
            cntLst.add( newcontact);
            
        }    
        if(!cntlst.isEmpty())  { 
            insert cntLst;
            
        } 
        
    } catch (Exception e) {
        for(sobject obj:accnew){
            objName = string.valueof(obj.getsobjecttype());
            system.debug('objName' + objName);
        }
        CustomHandleException.LogExceptionMethod(e, objName);
    }
}

Leave A Comment

All fields marked with an asterisk (*) are required