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?
- Download the ldsUtils component from here
- Deploy this component to your org.
-
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) : []; } }
- And call it by passing the error object. (3rd last line)
how to download?
ReplyDeleteHi 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.
DeleteHi Kaushik, just to git repo link mentioned in step1 and copy the code or download the whole repo.
ReplyDeleteHow to download? I do not see any option. All I see is copy paste
DeleteHi Praveen, yes you need to copy it code.
Delete