Simplify error handling in Lightning Web Components

Telegram logo Join our Telegram Channel
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


5 comments:
  1. Replies
    1. Hi Kaushik, just to git repo link mentioned in step1 and copy the code from ldsUtils.js file, create a new component with same name, delete html file and paste the code copied from git repo into ldsUtils.js of your project.

      Delete
  2. Hi Kaushik, just to git repo link mentioned in step1 and copy the code or download the whole repo.

    ReplyDelete
    Replies
    1. How to download? I do not see any option. All I see is copy paste

      Delete
    2. Hi Praveen, yes you need to copy it code.

      Delete

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com