Sub topic 2
Working with the Returned Promise
Assume you know JavaScript modules, Promises, LWC event handlers, and basic Apex. An imperative Apex call returns a JavaScript Promise. The Promise fulfills with the method's return value or rejects when Salesforce reports an error.
Awaiting the Result
Use async and await when the call should happen after an event, such as a button click. Put the call in try, handle failures in catch, and clean up in finally.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
errorMessage;
isLoading = false;
async handleSearch() {
this.isLoading = true;
this.errorMessage = undefined;
try {
this.contacts = await searchContacts({
searchTerm: this.searchTerm
});
} catch (error) {
this.contacts = [];
this.errorMessage =
error?.body?.message || error?.message || 'Search failed.';
} finally {
this.isLoading = false;
}
}
}finally runs whether the Promise fulfills or rejects. This makes it the right place to stop a spinner.
Showing a Loading State
Bind isLoading to a conditional template block. Disable the action while the request is active when repeated clicks would be wasteful.
<template lwc:if={isLoading}>
<lightning-spinner alternative-text="Loading contacts"></lightning-spinner>
</template>Throwing Useful Errors from Apex
Use AuraHandledException for expected, user-facing failures. Its message reaches the component without exposing an unnecessary server stack trace.
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
try {
update as user new Contact(Id = contactId, Email = email);
} catch (DmlException error) {
throw new AuraHandledException(error.getDmlMessage(0));
}
}Handling and Displaying Errors
Read the message from error.body.message when possible. Clear stale results after a failed search, and render the message with an error style.
> [!warning] > Do not display raw exception details to users when they might reveal sensitive data. Return a clear, actionable message from Apex.
<template lwc:if={errorMessage}>
<p class="slds-text-color_error">{errorMessage}</p>
</template>Exercise
Why should isLoading = false be placed in finally instead of only after await?
Show answer
finally runs after both fulfillment and rejection, so the spinner stops even when Apex fails.