Exception Handling And Save Log In Salesforce Object

Exception Handling is the best practice of robust app development and maintenance. In your project if you want to handle exception in proper way and save log in custom object. Then you can create a helper class(“ExceptionHandler“) and an custom object (“Error_Log__c“). What info you can log? You can log class name, method name, username, log time and error description.

So you custom object fields are::

Field Label Api Name Field Type Size
Class Name class_name__c Text 255
Method Name method_name__c Text 255
User username__c Lookup(User)
Log Time log_time__c DateTime 255
Error Description description__c TextArea(Long) 32000
Line Number Line__c Text 6
HTTP Status Code HTTP_Status_code__c Text 7

1. Log Apex Call-Out Error:

public class ExceptionHandler
{
    public static void logApexCalloutError(String className,String methodName,String lineno,HttpResponse response)
    {
	Error_Log__c log = new Error_Log__c();
	log.className__c = className;
	log.methodName__c = methodName;
	log.lineno__c = lineno;
	log.log_time__c=System.now();
	log.user__c = UserInfo.getUserId();
	
	// You can get HTTP Status Code and Response Body
	if(response!=null)
	{
		log.description__c=response.getBody();
		log.HTTP_Status_code__c =response.getStatusCode();			
	}
	Insert log;		
     }	
}

2. Exception Handling of Insert and Update Statements

If you insert or update record in bulk using Database.Insert() or Database.upsert() statement then use following method to save log. I think Salesforce Data Loader also use this technique to show insert and update result. But using following code you can log only failed record detail.

public class ExceptionHandler
{
    public static void logInsertORUpdateError(String className,String methodName,String lineno,List<Database.UpsertResult> saveResultList)
    {
        // In Error Log Custom object you can add an extra column Object name to save also object name
	List<Error_Log__c> logList = new List<Error_Log__c>();
        Transient Database.UpsertResult upsertResult;
        for (Integer index = 0; index < saveResultList.size(); index++) {        
                upsertResult = saveResultList[index];                                    
                //Use isSuccess() method of Database.UpsertResult class to is record inserted/updated or not
                if (!upsertResult.isSuccess()) {                    
                    Error_Log__c log= new Error_Log__c();                    
                    log.description__c = String.valueOf(upsertResult.getErrors()[0].getMessage());
                    log.className__c = className;
	            log.methodName__c = methodName;
	            log.lineno__c = lineno;
	            log.log_time__c=System.now();
	            log.user__c = UserInfo.getUserId();
                    if(upsertResult.getId() != null){
                        log.Object_Name__c = upsertResult.getId().getSobjectType().toString();
                    }
                    logList.add(log);                    
                }
          }
          if(!logList.isEmpty())
          {
               Database.insert(logList);
          }	
    }
}

Log insert error:

Above method only work for Database.upsert() statement. If you want to log Database.insert() statement errors too. Then you can write same code and change parameter List<Database.UpsertResult> by List<Database.InsertResult>.

You can call logInsertORUpdateError() method like –>

List upsertResObjList = upsert(recordToUpsert, externalIdField, allOrNone);
ExceptionHandler.logInsertORUpdateError('clsname',methodname,'212',upsertResObjList);

To learn more about Database statements please click here

Leave a Reply

Your email address will not be published. Required fields are marked *