Error Handling and User Feedback

Error handling should follow a consistent path: capture and normalize the error, show clear user feedback, and log enough detail for debugging without exposing sensitive data.

Handling Priorities

  • Protect the user experience with clear, actionable messages
  • Keep technical details out of user-facing text
  • Preserve diagnostic context in logs for troubleshooting
  • Keep UI state predictable (hasError, errorMessage, loading state)

Error Message Normalization

Usage: Normalize platform and JavaScript error shapes into one user-facing message.

Example:

getErrorMessage(error) {
    if (error?.body?.message) {
        return error.body.message;
    }
    if (Array.isArray(error?.body)) {
        return error.body.map((item) => item.message).join(', ');
    }
    if (error?.message) {
        return error.message;
    }
    return 'An unexpected error occurred. Please try again.';
}

Error States

Usage: Track error states and display accessible UI feedback.

Examples:

export default class MyComponent extends LightningElement {
    error;
    errorMessage;
    hasError = false;

    handleError(error) {
        this.error = error;
        this.hasError = true;
        this.errorMessage = this.getErrorMessage(error);
    }

    getErrorMessage(error) {
        if (error.body && error.body.message) {
            return error.body.message;
        }
        return 'An unexpected error occurred. Please try again.';
    }

    clearError() {
        this.error = undefined;
        this.hasError = false;
        this.errorMessage = undefined;
    }
}

Template:

<template>
    <!-- Good: Single element - lwc:if on the element itself -->
    <p lwc:if={hasError} class="error-message" role="alert">{errorMessage}</p>
    <template lwc:else>
        <!-- Normal content -->
    </template>
</template>

Wire Service Error Handling

Usage: Handle errors from wire adapters appropriately.

Examples:

@wire(getRecord, { recordId: '$recordId', fields: ACCOUNT_FIELDS })
wiredAccount({ error, data }) {
    if (data) {
        this.account = data;
        this.error = undefined;
        this.hasError = false;
    } else if (error) {
        this.error = error;
        this.hasError = true;
        this.handleWireError(error);
    }
}

handleWireError(error) {
    // Show toast notification
    this.showToast('Error', 'Failed to load account data', 'error');

    // Log error for debugging
    console.error('Wire error:', error);

    // Set error state for UI
    this.errorMessage = this.getErrorMessage(error);
}

Toast Notifications

Usage: Use ShowToastEvent to provide immediate feedback after successful or failed actions.

Examples:

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class MyComponent extends LightningElement {
    showToast(title, message, variant) {
        const event = new ShowToastEvent({
            title: title,
            message: message,
            variant: variant || 'info'
        });
        this.dispatchEvent(event);
    }

    handleSuccess() {
        this.showToast('Success', 'Operation completed successfully', 'success');
    }

    handleError(error) {
        this.showToast('Error', this.getErrorMessage(error), 'error');
    }
}

Toast Variants:

  • success - Green toast for successful operations
  • error - Red toast for errors
  • warning - Yellow toast for warnings
  • info - Blue toast for informational messages

Error Boundary Pattern

Usage: Use errorCallback to catch and handle child component errors gracefully.

Examples:

export default class MyComponent extends LightningElement {
    error;
    hasError = false;

    errorCallback(error, stack) {
        // Log error
        console.error('Component error:', error);
        console.error('Stack trace:', stack);

        // Set error state
        this.error = error;
        this.hasError = true;

        // Show user-friendly error
        this.showToast('Error', 'An error occurred. Please refresh the page.', 'error');
    }
}

Error Handling Best Practices

  • Always handle errors appropriately
  • Provide user-friendly error messages
  • Log errors for debugging
  • Show toast notifications for user feedback
  • Set error states for UI display
  • Don't expose sensitive information in error messages

Documentation


Change History

Version 1.0 - 2026-03-26

  • Added initial version history tracking for this document.

Last Updated: 2026-03-26 Version: 1.0