目录
Overview
Summary
Use Cases for Interacting with Salesforce Data
Handling Server Errors
Sample Code
Reference
Overview
Summary
Use Cases for Interacting with Salesforce Data
Handling Server Errors
Sample Code
Prerequisite:
1. Copy the
ldsUtils
folder from LWC recipes and include it in the force-app/main/default/lwc directory in your project. This component contains thereduceErrors
function.2. Import the
reduceErrors
function in your lwc js file.
1. Wire Property
import { LightningElement, api, wire } from "lwc";
// import reduceErrors method
import { reduceErrors } from "c/ldsUtils";
import getContactsBornAfter from "@salesforce/apex/ContactController.getContactsBornAfter";
export default class WireApexProperty extends LightningElement {
@api minBirthDate;
@wire(getContactsBornAfter, { birthDate: "$minBirthDate" })
contacts;
// handle server error with wire property
get errors() {
return (this.contacts.error) ?
reduceErrors(this.contacts.error) : [];
}
}
2. Wire Function
import { LightningElement, api, wire } from "lwc";
// import reduceErrors method
import { reduceErrors } from "c/ldsUtils";
import getContactsBornAfter from "@salesforce/apex/AccountController.getContactsBornAfter";
export default class WireApexFunction extends LightningElement {
@api minBirthDate;
errors;
@wire(getContactsBornAfter, { birthDate: "$minBirthDate" })
wiredContacts({ data, error }) {
// handle server error with wire function
if (error) this.errors = reduceErrors(error);
}
}
3. Call LDS Function / Apex Imperatively
import { LightningElement, api, wire } from "lwc";
import { reduceErrors } from "c/ldsUtils";
import getContactsBornAfter from "@salesforce/apex/AccountController.getContactsBornAfter";
export default class CallApexImperative extends LightningElement {
@api minBirthDate;
errors;
handleButtonClick() {
getContactsBornAfter({
birthDate: this.minBirthDate,
})
.then((contacts) => {
// code to execute if the promise is resolved
})
.catch((error) => {
this.errors = reduceErrors(error); // code to execute if the promise is rejected
});
}
}
Note:
1. Display error in pannel. Of course, you can also display via toast message.
<template>
<lightning-card>
<template if:true={contacts.data}>
<lightning-datatable
key-field="Id"
data={contacts.data}
columns={columns}
>
</lightning-datatable>
</template>
<template if:true={errors}>
<p>{errors}</p>
</template>
</lightning-card>
</template>
2. To force error, include following code in you apex controller.
throw new AuraHandledException('Forced error');
Reference
Handle Server Errors Unit | Salesforce Trailhead