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.
- Create a custom object
- Create the Apex class
- Sample Trigger
Create a Custom Object
Object Name: Error
API Name: Error__c
Fields:
Field Label | Field Name | Data Type |
Class Name | Class_Name__c | Text(100) |
Description | Description__c | Long Text Area(32768) |
Error Name | Name | Auto Number |
Method Name | Method_Name__c | Text(100) |
Object Name | Object_Name__c | Text(18) |
Stack Trace | Stack_Trace__c | Text(255) |
Type | Type__c | Text(100) |
User Id | User_Id__c | Text(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);
}
}