Troubleshooting API Failures with Log Frames

Oct 13, 2023


 

 

After completing this unit, you will able to:

1.  Introduction

2.  Custom Labels in Salesforce

3.  Understanding API Call Errors

4.  Create Custom Labels

5.  Setting Up Custom Objects and Fields

6.   Implementing Error Logging with Custom Labels

 

1.  Introduction

In the world of Salesforce development, making API calls is a routine task. These calls allow you to interact with external systems, retrieve data, and update records. However, the success of these calls is never guaranteed, as errors can occur for various reasons.

API calls are the lifeblood of data integration in Salesforce, allowing you to connect and exchange information with external systems. To enhance your Salesforce development and troubleshooting process, capturing API call errors in custom objects with custom fields is a powerful strategy. However, when errors occur during these API calls, it's crucial to capture and log them effectively. However, when errors occur during these API calls, it's crucial to capture and log them effectively. In this blog, we will explore the concept of error logging within Salesforce, focusing on a strategic approach that leverages custom labels to log errors from API calls. This approach is particularly valuable when custom labels are enabled in your Salesforce org.

 

2.  Custom Labels in Salesforce

Custom labels are a dynamic way to customize and manage text values in your Salesforce application. These labels can be modified without changing your code, making them an ideal choice for messages, labels, and error descriptions.

1.  When custom labels are enabled in your Salesforce org, you can strategically utilize them in your error logging process.
2.  Custom labels allow you to maintain error messages in multiple languages, enhancing user experience for a global audience.
3.  You can update these labels without modifying your code, reducing the risk of introducing new issues.
4.  By using custom labels for error messages, you ensure consistency across your application. This is especially important when multiple components or developers are involved.
5.  Custom labels can be customized for different user profiles or even specific integrations, tailoring error messages to the needs of various stakeholders.

 

3.  Understanding API Call Errors

API call errors in Salesforce can result from a multitude of factors, such as network issues, invalid authentication, request payload errors, or issues on the external system's side. When an error occurs, it's important to not only identify the problem but also log and handle it effectively to ensure that your application remains robust and responsive.

Handling errors from API calls is a critical aspect of ensuring the reliability and performance of your applications. Log frames provide a structured and systematic way to handle and document errors, allowing for efficient troubleshooting and resolution. By implementing a robust error-handling process that includes log frames, your Salesforce applications will be better equipped to handle unexpected challenges and deliver a more reliable user experience.

 

4.  Create Custom Labels

Creating custom labels in Salesforce is a straightforward process. Here are the steps to create custom labels:

1.  Log in to your Salesforce organization to create custom labels.

2.  Click on the Gear icon in the upper-right corner of the Salesforce homepage and select Setup from the dropdown menu.

3.  In the Quick Find box in the left-hand side, type Custom Labels. You'll see Custom Labels in the list of available options.

4.  Click on the New Custom Labels button. You'll be presented with a form to define your custom label. Complete the following fields:

            Name: This is a unique name for your custom label. It's used to reference the label in your code. In this example, we will give Name as isEligible.

            Short Description: Provide a short description to explain the purpose of the custom label. We give as the Name field.

            Categories: You can categorize your custom labels for better organization. This is optional.

            Value: What value you want to define. (In this example, we will write the true word, so if the custom label has true value only then we will create a Log object record otherwise not.)

5.  After you've defined your custom label, click the Save button to create the custom label.

Your custom label is now created and can be used in various parts of your Salesforce organization, including formulas, validation rules, Apex code, Visualforce pages, and Lightning components. This is the screenshot of the custom label:

 

 

To use your custom label in code, you can reference it like this:

String customLabelValue = Label.isEligible;

 

5.  Setting Up Custom Objects and Fields

To capture API call errors effectively, we need to create custom objects and fields in Salesforce. Here's how we can do it:

In this example, we will create custom object named Log and add custom fields to store information about API call errors as shown in the figure:

 

 

Once the custom object and fields are set up, we can implement error capture as part of our integration process.

 

6.  Implementing Error Logging with Custom Labels

Whenever an API call results in an error, capture the relevant information (error message, error code, request and response details, and timestamp) and create a record in your custom object. Here's the code to quickly identify, analyze, and troubleshoot issues.

We will achieve this using a wrapper class. So let's create wrapper class first like the below code:

public class FeeWrapper {
        @AuraEnabled
        public Boolean isSuccess{get; set;}
        @AuraEnabled
        public String resultData{get; set;}
        @AuraEnabled
        public String errorMessage{get; set;}       
    }

 

To implement a class that captures API call errors in Salesforce, we need to create an apex class that handles the error and logs the relevant information into a custom object with custom fields. Below is a simplified example to get you started:

 

public class LogUtil {
    public static void createLog(String endPoint, String reqMethodName, String reqBody, String resBody, String apexMethodName, String parameters, Boolean status, String errorMessage) {
        Log__c log = new Log__c();
        log.End_Point__c = endPoint;
        log.API_Method_Name__c = reqMethodName;
        log.Request_Body__c = reqBody;
        log.Response_Body__c = resBody;
        log.Method_Name__c = apexMethodName;
        log.Parameters__c = parameters;
        log.Status__c = status == true ? 'Pass' : 'Failed';
        log.Exception_Message__c = errorMessage;
        insert log;
    }
}

 

You will need to customize this code to match your Salesforce environment and the specific custom object and fields you've set up for error logging.

Remember to call this createLog method whenever an API call results in an error to capture the error details in your custom object.

To call the createLog Apex method whenever an API call results in an error, you need to incorporate this method into your existing code where API calls are made.

 

Below is an example of how to call the createLog method when an API call error occurs:

try{
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
    request.setMethod('GET');
    HttpResponse response = http.send(request);
           
    if(response.getStatusCode() != 200){
        wrapper.isSuccess = false;
        wrapper.resultData = '';
    }
    else {
        wrapper.isSuccess = true;
        wrapper.errorMessage = '';
        wrapper.resultData = response.getBody();              
    }
}
catch(Exception e){
    wrapper.isSuccess = false;
    wrapper.errorMessage = e.getMessage();
    wrapper.resultData = '';                
}
finally {
    if(Label.isEligible == 'true')  
        LogUtil.createLog(endPoint, 'POST', requestBody, response.getBody(), apexMethodName, apexMethoParemeter, wrapper.isSuccess, wrapper.errorMessage);
}

 

In this code snippet:
 
1.  A try-catch block surrounds the API call. If an exception is thrown within the try block, it means an error has occurred.
 
2.  Inside the catch block, you define the error code, error message, request details, and response details based on the information relevant to the specific error that occurred during the API call.
 
3.  You call the createLog method from the LogUtil class, passing in the error details as arguments.
 
Make sure to replace the placeholders with actual error details, and adapt this code to your specific use case and error handling logic. When an error occurs during the API call, this code will log the error details into your custom object with custom fields as previously defined.

Now it's done. By following these best practices, you can create a robust error-handling system that enhances your development workflow and ensures that issues are addressed efficiently.

I hope this blog helped you!