Forcetrails: Simplify error handling in Lightning Web Components

Hello, Trailmixers!!


Error handling, yes, if you have little experience of using wired adapters and wired apex method, you might have noticed that the error details you get in the results are different for different scenarios. 


Problem

The main problem in error handling is that there is a different structure for error in each scenario like wired apex, wired uiRecordApis, standard javascript errors, HTTP errors, or imperative calls errors.

Sometimes the actual message is in the error object itself, sometimes its in the body property of the error. Sometimes the error object contains an array of errors. So we need to handle these data structures differently.


The Solution

There is a component in the lwc-recipes github repository called ldsUtils. This component contains the reusable JavaScript module for error handling.

The only method reduceErrors from this component automatically detects the type of error and converts it into a human-readable format.

It extracts and flattens the error message(s). It handles all types of errors like LDS, Apex, uiApis, JS errors, and HTTP callout errors.


How to use that?

  1. Download the ldsUtils component from here
  2. Deploy this component to your org.
  3. Import it wherever needed like below (Line # 2 from the below code snippet).

    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) : [];
        }
    }
    

  4. And call it by passing the error object. (3rd last line)


References


No comments :
Post a Comment

Hi there, comments on this site are moderated, spams and promotions will be deleted. If you have any concern, or if you are not able to comment for some reason, reach email us at rahul@forcetrails.com