How to Handling Async Errors in LWC Record Creation?

How to Handling Async Errors in LWC Record Creation?

On April 2, 2025, Posted by , In Lightning web components,Salesforce, With Comments Off on How to Handling Async Errors in LWC Record Creation?

Question

The issue arises when creating a Case record and subsequently a related Case Detail record in a Lightning Web Component (LWC) used in Field Service Mobile (FSM). Approximately 5% of the time, the Case Detail record fails to be created. Debugging suggests that this is due to the way errors are handled during the asynchronous operations.

Problem with Current Error Handling

The existing implementation uses a try/catch block to handle errors, but this does not work effectively for asynchronous methods like createRecord. In JavaScript, try/catch works only for synchronous code and cannot catch errors from promises unless they are awaited or explicitly handled using .catch()
For example:

checkErrorHandling() {
    try {
        doSomething() // This returns a promise
        .then(() => {
            console.log('Operation successful');
        })
        .catch(() => {
            console.log('Error caught in inner catch');
        });
    } catch (err) {
        console.log('Error caught in outer catch'); // This will not catch promise errors
    }
    console.log('After all'); // Executes immediately
}

Here, errors thrown by the asynchronous doSomething() will not be caught by the outer try/catch block but need to be handled using the .catch() method.

Answer

Use async/await for Better Error Handling

Refactor the LWC’s method to use async/await, which allows proper handling of asynchronous errors with a try/catch block.

async handleCreate() {
    try {
        // Prepare Case record
        const fields = {
            [RECORDTYPEID_FIELD.fieldApiName]: this.caseRecordTypeId,
            [STATUS_FIELD.fieldApiName]: "Open",
            [SUBJECT_FIELD.fieldApiName]: `${this.caseType} - ${this.subType} - ${this.category}`.substring(0, 254),
        };
        const caseRecord = { apiName: CASE_OBJECT.objectApiName, fields };

        // Create the Case record
        const newCaseRecord = await createRecord(caseRecord);
        console.log('Case created:', newCaseRecord.id);

        // Prepare Case Detail record
        const caseDetailFields = {
            [RECORDTYPEID_CASEDETAIL_FIELD.fieldApiName]: this.caseDetailRecordTypeId,
            [CASE_CASEDETAIL_FIELD.fieldApiName]: newCaseRecord.id,
        };
        const caseDetailRecord = { apiName: CASEDETAIL_OBJECT.objectApiName, fields };

        // Create the Case Detail record
        const newCaseDetailRecord = await createRecord(caseDetailRecord);
        console.log('Case Detail created:', newCaseDetailRecord.id);

        // Update UI
        setTimeout(() => {
            this.showForm = false;
            this.showReview = false;
            this.showSubmitted = true;
        }, 2000);
    } catch (error) {
        console.error('Error during record creation:', error);

        const appLogValues = {
            errmsg: `Error: ${error.message}`,
            errtype: 'FSM LWC Error',
            sourceclass: 'LWC.newCase.js',
            sourcefunc: 'handleCreate',
            loglevel: 'ERROR',
            stacktrace: error.stack || 'No stack trace',
        };
        this.createApplicationLog(appLogValues);

        this.dispatchEvent(new ShowToastEvent({
            title: 'Error',
            message: error.message,
            variant: 'error',
            mode: 'sticky',
        }));
    }
}

Key Changes and Improvements:

  1. Using async/await:
    • createRecord is an asynchronous method. Instead of chaining .then() and .catch(), await is used to pause execution until the record is created.
    • If an error occurs during the await, it is directly caught by the surrounding try/catch block, making error handling consistent and straightforward.
  2. Error Handling in a Single catch Block:
    • Any error, whether it occurs during the creation of the Case or the Case Detail, is handled by the same catch block.
    • This ensures a unified error-handling mechanism and avoids the need for nested error handling.
  3. Application Log Creation:
    • If an error occurs, the createApplicationLog method is called to log details about the error, such as the error message, source class, and function.
  4. Toast Notification:
    • A toast is displayed to the user using the getToastEvent method, ensuring that the user is informed about the error.
  5. Transitioning the UI on Success:
    • When both records are successfully created, the UI transitions to show a “Submitted” state after a brief delay using setTimeout.

Why This Approach is Better:

Maintainability: Logging errors and showing toast notifications are encapsulated in methods (createApplicationLog and getToastEvent), making the code modular and easier to maintain.

Readability: The use of async/await makes the flow of the code more readable and easier to understand, as it mimics synchronous execution.

Consistent Error Handling: The try/catch structure ensures all asynchronous errors are handled in one place, avoiding the pitfalls of mixing try/catch with .then() chains.

This structure ensures that both records are created sequentially, errors are properly logged and displayed, and the code is clean and easy to follow.

Enroll for Career-Building Salesforce Training with 100% Money Back Guarantee

Our Salesforce Course is designed to provide a comprehensive understanding of the Salesforce platform, equipping you with the key skills required to thrive in the CRM industry. The program focuses on critical modules like Salesforce Admin, Developer, and AI, combining theoretical insights with hands-on practical learning. By working on real-world projects and assignments, you’ll develop the confidence and expertise to solve complex business challenges using Salesforce solutions. Our seasoned trainers ensure you gain both technical knowledge and valuable industry insights to excel in the Salesforce ecosystem.

Beyond technical training, our Salesforce Training in Australia offers customized mentoring, certification preparation, and interview guidance to enhance your career potential. With access to detailed study materials, practical project experience, and dedicated support, you’ll be fully prepared for certification exams and equipped with problem-solving abilities that employers value. Take the first step toward your Salesforce career today and unlock endless possibilities. Enroll for a Free Demo session

Comments are closed.