Lightning Web Component

Throw Exception from Apex to LWC

You may come across situations where you need to throw an exception in your Apex code because it's not adhering to the business rules and then handle it gracefully in your Lightning Web Component (LWC). In this article, we'll discuss how to do this seamlessly.

Throw Exception from Apex to LWC

Throw Exception in Apex

Here, we will use AuraHandledException, a standard exception in Salesforce. It was specifically designed for use in the context of Aura component development. You can use it to show errors in LWC from your server-side controller methods, and the Aura framework will handle it.

In the following example, you can handle exceptions during DML operations in Apex. Specifically, you can retrieve and process validation rule messages when records fail to meet validation criteria before they get inserted/updated.

public class DMLExceptionHandler {
    public static void performDML() {
        try {
            // Perform your DML operation, (Account is missing the Name)
            Account acc = new Account();
            insert acc;
        } catch (DmlException e) {
            // Handle the exception if the DML operation fails
            List<String> excList = new List<String>();
            for (Integer i = 0; i < e.getNumDml(); i++) {
                System.debug('DML Exception: ' + e.getDmlMessage(i));
                excList.add(e.getDmlMessage(i));
            }
            throw new AuraHandledException(String.join(excList, ', '));
    	}
	}
}

Handling the Exception in LWC

Once you've caught an exception in the Apex class, you can display an error message on the UI to inform the user about the issue. To achieve this, you can use a variety of UI components or approaches, depending on your application's design.

import { LightningElement } from 'lwc';
import performDML from '@salesforce/apex/DMLExceptionHandler.performDML';

export default class ControlException extends LightningElement {
    handleClick() {
        performDML()
            .then(result => {
                // Logic if it the records were inserted successfully
                console.log(result);
            })
            .catch(error => {
                // Logic to handle the exception thrown from Apex
            });
    }
}

Toast Messages

You can use the lightning/platformShowToastEvent module to create and display toast messages with error details. Toast messages are temporary notifications that appear at the top of the page. Here's an example of how to display a toast message in LWC.

Don't forget to import the ShowToastEvent from lightning/platformShowToastEvent

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import performDML from '@salesforce/apex/DMLExceptionHandler.performDML';

export default class ControlException extends LightningElement {
    handleClick() {
        performDML()
            .then(result => {
                // Logic if it the records were inserted successfully
                console.log(result);
            })
            .catch(error => {
                const event = new ShowToastEvent({
                    title: 'Error',
                    message: error.message,
                    variant: 'error',
                });
                this.dispatchEvent(event);
            });
    }
}
ShowToastEvent handled error in LWC

Inline Error Messages

For form-based interactions, you can display inline error messages next to the specific fields or inputs that caused the error. This provides immediate feedback to the user.

<template>
    <lightning-input type="text" label="Name" class="name-input">
    </lightning-input>
</template>

On the Javascript, you must use setCustomValidity(message) to specify the error message on the input.

handleClick() {
    performDML()
        .then(result => {
            // Logic if it the records were inserted successfully
            console.log(result);
        })
        .catch(error => {
            const input = this.template.querySelector('.name-input');
            input.setCustomValidity(error.body.message); // SET ERROR MESSAGE
            input.reportValidity(); // DISPLAY THE MESSAGE ON THE INPUT
        });
}

removeErrorMessage(){
    const input = this.template.querySelector('.name-input');

    input.setCustomValidity('');
    input.reportValidity();
}
Display error on LWC field

Error Logging

In addition to displaying errors on the UI, consider logging errors for debugging and monitoring purposes. You can use console.error() to log errors to the browser's console or send error information to a logging service.

handleClick() {
    performDML()
        .then(result => {
            // Logic if it the records were inserted successfully
            console.log(result);
        })
        .catch(error => {
            console.error(error);
        });
}
Exception error from Apex controller to LWC
When displaying error messages to users, it's important to make them user-friendly and informative. Avoid displaying technical error details that may confuse users. Instead, provide clear and actionable messages that explain the issue and, if possible, suggest how to resolve it.