Error Handling in LWC – try/catch + Toast Messages

Proper error handling improves user experience and helps you debug issues faster. This guide covers try/catch handling in LWC and showing toast notifications.

1. Handling Imperative Apex Errors


import { LightningElement, track } from 'lwc';
import saveAccount from '@salesforce/apex/AccountController.saveAccount';

export default class AccountForm extends LightningElement {
    @track error;

    async handleSave() {
        try {
            await saveAccount({ accountName: this.accountName });
        } catch (error) {
            this.error = this.getErrorMessage(error);
            this.showToast('Error', this.error, 'error');
        }
    }

    getErrorMessage(error) {
        if (error.body) {
            return error.body.message || JSON.stringify(error.body);
        }
        return error.message || 'Unknown error';
    }
}
  

2. Using Lightning Toasts


import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ToastExample extends LightningElement {
    showToast(title, message, variant) {
        const event = new ShowToastEvent({
            title,
            message,
            variant,
        });
        this.dispatchEvent(event);
    }
}
  

Common variants

3. Error Handling with @wire


import { LightningElement, wire, track } from 'lwc';
import getRecords from '@salesforce/apex/RecordController.getRecords';

export default class WiredData extends LightningElement {
    @track data;
    @track error;

    @wire(getRecords)
    wiredData({ error, data }) {
        if (data) {
            this.data = data;
            this.error = undefined;
        } else if (error) {
            this.error = this.getErrorMessage(error);
            this.showToast('Load failed', this.error, 'error');
        }
    }

    getErrorMessage(error) {
        if (Array.isArray(error.body)) {
            return error.body.map(e => e.message).join(', ');
        } else if (error.body && error.body.message) {
            return error.body.message;
        }
        return error.message || 'Unknown error';
    }
}
  

4. Global Error Handling Pattern


export default class ErrorUtils {
    static getErrorMessage(error) {
        if (Array.isArray(error.body)) {
            return error.body.map(e => e.message).join(', ');
        } else if (error.body && error.body.message) {
            return error.body.message;
        }
        return error.message || 'Unknown error';
    }

    static showToast(component, title, message, variant = 'error') {
        component.dispatchEvent(
            new ShowToastEvent({
                title,
                message,
                variant,
            })
        );
    }
}
  

5. Displaying Inline Validation Errors

Show errors next to form fields for better usability.


<template>
    <lightning-input
        label="Email"
        type="email"
        value={email}
        onchange={handleEmailChange}
        message-when-bad-input={emailError}
        class={emailClass}
    ></lightning-input>
</template>
  

6. Best Practices