Error Logging Framework in Salesforce for Lightning Web Components (LWC) | #salesforce #lwc #sfdc : [email protected] (Kapil)

Error Logging Framework in Salesforce for Lightning Web Components (LWC) | #salesforce #lwc #sfdc
by: [email protected] (Kapil)
blow post content copied from  Salesforce Bolt
click here to view original post



### Summary of the Error Logging Framework for Salesforce Errors are common in software development, especially when using Salesforce's Lightning Web Components (LWC). This post introduces a reusable error logging framework designed to help developers manage errors more effectively. Here’s a breakdown of what it offers: #### Key Features: 1. **Error Capture**: The framework captures client-side errors in a user-friendly manner. 2. **User Notifications**: It displays meaningful error messages to users instead of cryptic alerts. 3. **Error Logging**: Technical details of errors are logged into Salesforce for future reference. 4. **Future Expansion**: The framework is designed to eventually support error reporting for Apex, Flow, and Batch processes. #### Components of the Framework: 1. **Custom Object**: `Error_Log__c` - This stores all logged errors, allowing teams to generate reports and dashboards. 2. **Apex Class**: `ErrorLoggingService.cls` - Contains methods to log errors from LWC and Flow, capturing essential details like source name, method name, error message, and stack trace. 3. **LWC Utility**: `errorHandler.js` - A JavaScript module that simplifies error logging in LWC by parsing errors and calling the Apex logging method. 4. **LWC UI Component**: `errorDisplay` - A user interface component that displays error messages and allows users to view stack traces if needed. 5. **Demo Component**: An example LWC is included to test the framework by simulating runtime errors. #### Benefits: - **Reusability**: The framework can be used across different projects. - **Faster Debugging**: Helps development teams identify and resolve issues quickly. - **User-Friendly**: Keeps users informed without exposing technical details. - **Data-Driven Insights**: Enables the creation of dashboards and alerts based on logged errors. #### Future Enhancements: - Support for logging errors from Flow and Batch processes. - Customizable notifications via platforms like Slack or email. The framework is open-source and available on GitHub for developers to explore and contribute to. 🔗 **GitHub Repository**: [Error Logging Framework](https://ift.tt/Tf7pQcK) ### Additional Context This framework is particularly useful for Salesforce developers who work with LWC, as it streamlines the error handling process and enhances user experience. By centralizing error logging, teams can improve their applications' reliability and maintainability. ### Hashtags for SEO #Salesforce #LightningWebComponents #ErrorLogging #Apex #WebDevelopment #Debugging #OpenSource #SoftwareDevelopment #SalesforceDevelopment #ErrorHandling


 


Errors happen. But in Salesforce, especially when working with Lightning Web Components (LWC), it’s easy for runtime issues to get lost in browser consoles or surface as cryptic toasts.

In this post, I’m introducing a reusable and extendable error logging framework that helps you:

  • Capture client-side (LWC) errors elegantly
  • Display meaningful messages to users
  • Log technical details to Salesforce
  • Lay the foundation for centralizing error reporting across Apex, Flow, and Batch in the future

📂 GitHub Repository:
👉 Error Logging Framework – GitHub


What’s Included

1. Custom Object: Error_Log__c

Stores every logged error for team reference.
You can later build reports or dashboards on top of it.


We use standard CreatedDate and CreatedById fields to know when and who triggered the error.

2. ErrorLoggingService.cls (Apex Class)

This class exposes a method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public with sharing class ErrorLoggingService {
    @AuraEnabled
    public static void logClientError(String componentName, String methodName, String message, String stack) {
        logError(componentName, methodName, message, stack, 'LWC', 'Medium', null, null);
    }

    public static void logError(String sourceName, String methodName, String message, String stackTrace, String sourceType, String severity, Id userId, Id relatedRecordId) {
        try {
            Error_Log__c log = new Error_Log__c();
            log.Source_Name__c = sourceName;
            log.Method_Name__c = methodName;
            log.Error_Message__c = message;
            log.Stack_Trace__c = stackTrace;
            log.Source_Type__c = sourceType;
            log.Severity__c = severity;
            log.Related_Record_Id__c = relatedRecordId;
            insert log;
        } catch (Exception ex) {
            System.debug('Failed to log error: ' + ex.getMessage());
        }
    }

    @InvocableMethod(label='Log Error from Flow')
    public static void logErrorFromFlow(List<FlowErrorWrapper> errors) {
        List<Error_Log__c> errorLogs = new List<Error_Log__c>();
        for (FlowErrorWrapper err : errors) {
            Error_Log__c log = new Error_Log__c();
            log.Source_Name__c = err.Source_Name;
            log.Method_Name__c = err.Method_Name;
            log.Error_Message__c = err.Error_Message;
            log.Stack_Trace__c = err.Stack_Trace;
            log.Source_Type__c = 'Flow';
            log.Severity__c = err.Severity;
            log.Related_Record_Id__c = err.Related_Record_Id;
            errorLogs.add(log);
        }
        if (!errorLogs.isEmpty()) {
            insert errorLogs;
        }
    }

    public class FlowErrorWrapper {
        @InvocableVariable(label='Source Name')
        public String Source_Name;

        @InvocableVariable(label='Method Name')
        public String Method_Name;

        @InvocableVariable(label='Error Message')
        public String Error_Message;

        @InvocableVariable(label='Stack Trace')
        public String Stack_Trace;

        @InvocableVariable(label='Severity')
        public String Severity;

        @InvocableVariable(label='Related Record Id')
        public Id Related_Record_Id;
    }
}

It inserts the captured error into the custom object. The current implementation supports LWC, and will be extended soon to support Apex, Flow, and Batch errors using overloads and @InvocableMethod.


3. LWC Utility: errorHandler.js

This JavaScript module makes logging errors effortless in any LWC:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// errorHandler.js
import logErrorToSalesforce from '@salesforce/apex/ErrorLoggingService.logClientError';

export async function handleError(componentName, methodName, error, severity = 'Medium', relatedRecordId = null, callback) {
    const errorMessage = extractErrorMessage(error);
    const stack = error?.stack || '';
    console.error(`[${componentName} > ${methodName}]`, errorMessage);

    try {
        await logErrorToSalesforce({
            componentName,
            methodName,
            message: errorMessage,
            stack,
            severity,
            relatedRecordId
        });
    } catch (e) {
        console.warn('Failed to log error in Salesforce:', e);
    }

    if (typeof callback === 'function') {
        callback({ message: errorMessage, stack });
    }
}

function extractErrorMessage(error) {
    if (typeof error === 'string') return error;
    if (error.body?.message) return error.body.message;
    if (error.message) return error.message;
    return JSON.stringify(error);
}


What it does:

  • Parses the error safely
  • Calls Apex to log it
  • Allows optional UI display

4. LWC UI Component: errorDisplay

Use this lightweight component to show errors clearly inside your UI:

HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<template>
    <div class="slds-var-m-vertical_small">
        <span class="slds-text-color_destructive">
            {errorMessage}.
            <template lwc:if={stackTrace}>
                <a onclick={handleShowDetailsClick}> Show details.</a>
            </template>
        </span>
        <template lwc:if={viewDetails}>
            <p class="slds-text-body_regular">
                {stackTrace}
            </p>
        </template>
    </div>
</template>


JS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { LightningElement, api } from 'lwc';

export default class ErrorDisplay extends LightningElement {
    @api errorMessage;
    @api stackTrace;
    @api visible = false;
    viewDetails = false;

    handleShowDetailsClick() {
        this.viewDetails = !this.viewDetails;
    }
}


Fully styled with SLDS — no custom CSS!


5. Example Component

A demo LWC is included to help you test the framework:

  • Click a button to simulate a runtime error
  • The error is caught, displayed, and logged in Salesforce
  • You can view the error under the Error_Log__c object

Perfect for testing in App Builder or Developer Console.


Demo Available for: LWC

This version of the framework currently supports Lightning Web Components only.

Apex, Flow, and Batch support is being designed and will be integrated soon with minimal changes.


Benefits

  • Reusable across projects
  • Helps dev teams debug issues faster
  • Keeps users informed without exposing stack traces
  • Easily build dashboards or alerts from logged errors


Try It Now

All code is open-source and documented.
🔗 GitHub: https://github.com/batra-kapil/Error-Logging-Framework


Coming Soon:

  • Flow Fault Logging via Invocable Apex
  • Batch Job Try-Catch Integration
  • Customizable Notification Support (Slack/Email)


Build resilient Salesforce apps. Log it. Debug it. Improve it.
Let me know what you think or open a PR if you want to contribute!


Checkout Complete Video Below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

May 31, 2025 at 06:29PM
Click here for more details...

=============================
The original post is available in Salesforce Bolt by [email protected] (Kapil)
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce