Exception in LWC

How to Throw an exception in LWC:

Using:

  1. Handling Errors on Wired Properties
  2. wireApexFunction.js
  3. callApexImperative.js

Use: ldsUtils provide by salesforce.

The reduceErrors helper function in this example comes from the ldsUtils module of the LWC Recipes sample app. LWC Recipes contains easy-to-digest examples of common patterns implemented as Lightning web components. Feel free to copy the ldsUtils module into your project, and use the reduceErrors function.

Create a component with :

https://github.com/trailheadapps/lwc-recipes/tree/master/force-app/main/default/lwc/ldsUtils

**Make is Expose true in Meta.xml

Example to Show how to use the 'AuraHandledException' in LWC:

Apex class:

AccountController.cls

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        throw new AuraHandledException('Forced error  LWC------->');
        //we are commenting return Statment. Throw exception.
    }
}

accountList.html

<template>
    <lightning-card>
        <template if:true={errors}>           
                <p>{errors}</p>            
        </template>
    </lightning-card>
</template>

accountList.js

import { LightningElement, wire } from 'lwc';
import { reduceErrors } from 'c/ldsUtils';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
const COLUMNS = [
    { label: 'Account Name', fieldName: NAME_FIELD.fieldApiName, type: 'text' },
    { label: 'Annual Revenue', fieldName: REVENUE_FIELD.fieldApiName, type: 'currency' },
    { label: 'Industry', fieldName: INDUSTRY_FIELD.fieldApiName, type: 'text' }
];
export default class AccountList extends LightningElement {
    columns = COLUMNS;
    @wire(getAccounts)
    accounts;

    get errors(){
        return (this.accounts.error) ?
            reduceErrors(this.accounts.error) : [];
    }
    
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="<http://soap.sforce.com/2006/04/metadata>">
   <apiVersion>45.0</apiVersion>
   <isExposed>true</isExposed>
   <targets>
       <target>lightning__AppPage</target>
       <target>lightning__RecordPage</target>
       <target>lightning__HomePage</target>
   </targets>
</LightningComponentBundle>

Output:

for details of each line : https://trailhead.salesforce.com/content/learn/modules/lightning-web-components-and-salesforce-data/handle-server-errors

Syntax:

1.Handling Errors on Wired Properties

import { LightningElement, api, wire } from 'lwc';
import { reduceErrors } from 'c/ldsUtils';
import getRelatedContacts from '@salesforce/apex/AccountController.getRelatedContacts';
export default class WireApexProperty extends LightningElement {
    @api recordId;
    @wire(getRelatedContacts, { accountId: '$recordId' })
    contacts;
    get errors() {
        return (this.contacts.error) ?
            reduceErrors(this.contacts.error) : [];
2.wireApexFunction.js

import { LightningElement, api, wire } from 'lwc';
import { reduceErrors } from 'c/ldsUtils';
import getRelatedContacts from '@salesforce/apex/AccountController.getRelatedContacts';
export default class WireApexFunction extends LightningElement {
    @api recordId;
    errors;
    @wire(getRelatedContacts, { accountId: '$recordId' })
    wiredContacts({data, error}) {
        if (error)
            this.errors = reduceErrors(error);
    }
}
3.callApexImperative.js
import { LightningElement, api, wire } from 'lwc';
import { reduceErrors } from 'c/ldsUtils';
import getRelatedContacts from '@salesforce/apex/AccountController.getRelatedContacts';
export default class CallApexImperative extends LightningElement {
    @api recordId;
    errors;
    handleButtonClick() {
        getRelatedContacts({
            accountId: '$recordId'
        })
            .then(contacts => {
                // code to execute if the promise is resolved
            })
            .catch(error => {
                this.errors = reduceErrors(error); // code to execute if the promise is rejected
            });
    }
}

HTML

<template>
    <template if:true={errors}>
        <p>{errors}</p>
    </template>
</template>


The solution to Trailhead Module :

Handle errors in a component.

In the contactList component, use the reduceErrors function to handle errors and display error messages in the component markup.

Tip: Remember that JavaScript is a case-sensitive programming language. Be careful to use uppercase and lowercase letters correctly.

  • Show errors in the contactList markup
  • Add the ldsUtils component from LWC recipes to your project
  • Define a getter for a property named errors and use the reduceErrors function in the getter
  • Force the Apex class to throw an AuraHandledException to see an error on the contactList component
  • Deploy the changes to your Trailhead Playground


Create 
ContactList.html
<template>
    <lightning-card>
        <template if:true={errors}>
            <template if:true={errors}>           
                <p>{errors}</p>            
            </template>
        </template>
    </lightning-card>
</template>

ContactList.js
import { LightningElementwire } from 'lwc';
import { reduceErrors } from 'c/ldsUtils';
import FIRSTNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
    { label: 'First Name'fieldName: FIRSTNAME_FIELD.fieldApiNametype: 'text' },
    { label: 'Last Name'fieldName: LASTNAME_FIELD.fieldApiNametype: 'text' },
    { label: 'Email'fieldName: EMAIL_FIELD.fieldApiNametype: 'Email' }
];
export default class ContactList extends LightningElement {
    columns = COLUMNS;
    @wire(getContacts)
    Contacts;

    get errors(){
        return (this.Contacts.error) ?
            reduceErrors(this.Contacts.error) : [];
    }

}


xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
   <apiVersion>45.0</apiVersion>
   <isExposed>true</isExposed>
   <targets>
       <target>lightning__AppPage</target>
       <target>lightning__RecordPage</target>
       <target>lightning__HomePage</target>
   </targets>
</LightningComponentBundle>

create apex class to throw the exception:
ContactController.cls
public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<ContactgetContacts() {
       throw new AuraHandledException('Trailhead Module Solution @Force Exception throw');
       /* return [
            SELECT FirstName, LastName, Email
            FROM Contact
            WITH SECURITY_ENFORCED
            ORDER BY firstName
        ];*/
    }
}





Deploy:
1. Class then  ldsUtils then  ContactList by right click on folder. follow steps given ontrailhead

Output:

                             







Comments

Popular posts from this blog

LearnSalesforce

LWC Interview Questions Part-1

Lightning Web Component