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!
0 Comments