About Me

My photo
PLANO, Texas, United States

Friday, October 16, 2020

Handle Errors in LDS

Any system can generate errors but the important thing is how to handle this.

Lightning Data Service returns an error when a resource, such as a record or an object, is inaccessible on the server.

For example, an error occurs if you pass in an invalid input to the wire adapter, such as an invalid record Id or missing required fields. An error is also returned if the record isn’t in the cache and the server is offline. Also, a resource can become inaccessible on the server when it’s deleted or has its sharing or visibility settings updated.

Error Values

The FetchResponse error object contains the body of the response and a status code and message.

  • body (Object or Array)—The body of the response, which is defined by the underlying API.

  • ok (Boolean)—Specifies whether the response was successful or not. For an error, ok is always false and contains a status in the range 400–599.

  • status (Number)—Contains the status code of the response, for example, 404 if a resource is not found or 500 for an internal server error.

  • statusText (String)—Contains the status message corresponding to the status code, for example, NOT_FOUND for a status code of 404.


<template>

   <lightning-card title="Handle Error">

       <template if:true={error}>

           <p>{error}</p>

       </template>

   </lightning-card>

</template>



import { LightningElement, api, wire, track } from 'lwc';

import { getRecord } from 'lightning/uiRecordApi';

 

export default class WireGetRecordDynamicContact extends LightningElement {

   @api recordId;

   @track error;

   @wire(getRecord, { recordId: '$recordId', fields })

   wiredRecord({error, data}) {

       if (error) {

           this.error = 'Unknown error';

           if (Array.isArray(error.body)) {

               this.error = error.body.map(e => e.message).join(', ');

           } else if (typeof error.body.message === 'string') {

               this.error = error.body.message;

           }

           this.record = undefined;

       } else if (data) {

           // Process record data

       }

   }

}


No comments:

Post a Comment