Sub topic 8
Throwing and displaying errors
When an @AuraEnabled method fails, the component needs a message it can show to the user. This chapter covers how to throw errors from Apex, what the browser receives, and how to display them for both @wire and imperative calls.
This chapter assumes you can write a basic @AuraEnabled controller, you have used @wire and imperative calls in a Lightning web component, and you know how try/catch and DmlException work in Apex.
What the client receives when Apex fails
Any uncaught exception in an @AuraEnabled method rejects the call. The result differs by exception type:
| Exception thrown | What the component sees |
|---|---|
| `AuraHandledException` | `error.body.message` holds the message you set |
| Any other exception (`DmlException`, `QueryException`, `NullPointerException`) | A generic message such as "An internal server error has occurred" in most orgs. Details are hidden to avoid leaking internals |
| Limit exceptions (CPU time, heap, SOQL queries) | The same generic failure. Apex cannot catch these |
So you catch the exceptions you expect and rethrow them as AuraHandledException, with a message written for the end user.
Throwing AuraHandledException
Pass the message to the constructor and throw. There is one known gotcha. If you read getMessage() on an AuraHandledException in Apex, for example in a test, it returns "Script-thrown exception" unless you also call setMessage(). The client still gets your message, but your tests will not. A small factory method avoids the problem.
public with sharing class ContactService {
@AuraEnabled
public static Contact createContact(String lastName, Id accountId) {
if (String.isBlank(lastName)) {
throw auraError('Last name is required.');
}
try {
Contact c = new Contact(LastName = lastName, AccountId = accountId);
insert as user c;
return c;
} catch (DmlException e) {
String reason = e.getNumDml() > 0 ? e.getDmlMessage(0) : e.getMessage();
throw auraError('Could not create the contact: ' + reason);
}
}
private static AuraHandledException auraError(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}
}Three points about this code:
- The blank-name check is validation you control, so it throws directly with no
tryblock. getDmlMessage(0)returns only the field-level text, for example "Required fields are missing: [LastName]".getMessage()includes extra prefixes such asINSERT failed. First exception on row 0. ThegetNumDml()check guards against aDmlExceptionwith no row details.insert as userenforces object and field permissions. A failure there surfaces as an exception too, so the same handling applies.
Write messages for users, log details for admins
Do not forward raw exception text such as stack traces, record IDs, or query strings to the browser. Show a friendly message to the user and keep the technical detail where an admin can find it, such as a System.debug line during development or a custom logging object in production.
} catch (QueryException e) {
System.debug(LoggingLevel.ERROR, 'getSummary failed: ' + e.getStackTraceString());
throw auraError('We could not load the account summary.');
}Should read methods catch errors?
Yes, when you can say something useful. A cacheable=true method that runs a single-record SOQL query with no matching row throws QueryException ("List has no rows for assignment"). The component would see a generic failure. Catching it and throwing an AuraHandledException such as "That account no longer exists." is a better experience. Remember that cacheable methods cannot perform DML, so their errors are almost always query, access, or null-reference problems.
Reading the error in JavaScript
Both call styles give you an error object with the same shape for Apex failures:
error.body.messageis the string from the server.error.bodymay instead be an array, or containfieldErrorsandpageErrors, when the failure came from a UI API call such aslightning/uiRecordApi.- Errors that never reached the server, such as a network failure or a JavaScript bug inside your
tryblock, are plainErrorobjects witherror.messageand nobody.
Handling every shape inline gets repetitive, so put the logic in a shared module. In an LWC project, create force-app/main/default/lwc/errorUtils/errorUtils.js:
export function reduceErrors(errors) {
if (!Array.isArray(errors)) {
errors = [errors];
}
return errors
.filter((error) => !!error)
.map((error) => {
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message);
}
if (error.body && typeof error.body.message === 'string') {
return error.body.message;
}
if (typeof error.message === 'string') {
return error.message;
}
return 'Unknown error';
})
.reduce((prev, curr) => prev.concat(curr), [])
.filter((message) => !!message);
}The function always returns an array of strings, whatever the input. That lets the template loop over messages without checking types.
Displaying errors from an imperative call
Imperative calls return a promise. A failed call rejects it, so use try/catch with await. Choose where the message appears: in the template for errors that belong to a form, or in a toast for transient feedback.
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import createContact from '@salesforce/apex/ContactService.createContact';
import { reduceErrors } from 'c/errorUtils';
export default class ContactCreator extends LightningElement {
@api recordId;
lastName = '';
errors = [];
isSaving = false;
handleChange(event) {
this.lastName = event.target.value;
}
async handleSave() {
this.isSaving = true;
this.errors = [];
try {
const contact = await createContact({
lastName: this.lastName,
accountId: this.recordId
});
this.dispatchEvent(
new ShowToastEvent({
title: 'Contact created',
message: contact.Id,
variant: 'success'
})
);
} catch (error) {
this.errors = reduceErrors(error);
} finally {
this.isSaving = false;
}
}
get hasErrors() {
return this.errors.length > 0;
}
}The matching template:
<template>
<lightning-card title="New contact">
<div class="slds-var-p-around_medium">
<lightning-input label="Last name" onchange={handleChange}></lightning-input>
<lightning-button label="Save" onclick={handleSave} disabled={isSaving}></lightning-button>
<template lwc:if={hasErrors}>
<ul class="slds-text-color_error" role="alert">
<template for:each={errors} for:item="message">
<li key={message}>{message}</li>
</template>
</ul>
</template>
</div>
</lightning-card>
</template>The component clears errors at the start of each attempt, so a message from a previous failure does not stay visible after a retry succeeds. The finally block re-enables the button whether the call succeeded or failed. The role="alert" attribute makes screen readers announce the message when it appears.
Displaying errors from a wired call
A wire service does not throw. It provisions a value with two fields, data and error. If you wire to a property, error is reachable as this.contacts.error. If you wire to a function, the function receives both:
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import { reduceErrors } from 'c/errorUtils';
export default class ContactListWithErrors extends LightningElement {
@api recordId;
contacts = [];
errors = [];
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data, error }) {
if (data) {
this.contacts = data;
this.errors = [];
} else if (error) {
this.contacts = [];
this.errors = reduceErrors(error);
}
}
}Both branches reset the other state. The wire service reruns when $recordId changes, and a stale error or stale rows from the previous run should not remain on screen.
The wire function is also called with { data: undefined, error: undefined } while the parameter is still undefined, so neither branch runs in that case. Check this before assuming a missing data means a failure.
Choosing where to show the message
- Inline text near the control fits validation and form errors, because the user needs to fix something there.
- A toast fits one-off feedback after an action, such as "Contact created" or a failure the user cannot fix by editing a field.
- An empty-state message in place of the content fits failed reads, where the component has nothing to display.
Testing the error path
Test the error path as deliberately as the success path. Assert on the message, which works only because auraError calls setMessage().
@IsTest
private class ContactServiceTest {
@IsTest
static void blankLastNameThrowsFriendlyError() {
Account a = new Account(Name = 'Test Account');
insert a;
try {
ContactService.createContact('', a.Id);
Assert.fail('Expected an AuraHandledException');
} catch (AuraHandledException e) {
Assert.areEqual('Last name is required.', e.getMessage());
}
}
}Assert.fail throws an AssertException, which is not an AuraHandledException, so the catch block does not swallow it. If the method fails to throw, the test fails as it should.
Common mistakes
- Catching
Exceptionand returningnull. The component then cannot tell failure from an empty result. - Throwing
AuraHandledExceptionwithoutsetMessage()and then asserting on the message in tests. - Reading
error.messageinstead oferror.body.messagefor Apex errors. - Leaving an old error visible after a successful retry.
- Surfacing internal details such as SOQL text or stack traces in the message.
Exercise
A cacheable Apex method getSummary(Id accountId) runs SELECT Name FROM Account WHERE Id = :accountId into a single Account variable. A user opens the component for an account that was just deleted, and the component shows only "An internal server error has occurred". What change in Apex gives the user a useful message, and how does the wired component display it?
Show answer
Catch the QueryException thrown when the query returns no row (or query into a list and check for empty), log the technical detail server side, and throw an AuraHandledException with a user-facing message such as "That account no longer exists." Call setMessage() with the same text so tests can read it. In the component, handle the error branch of the wired function (or this.summary.error), pass it through reduceErrors, and render error.body.message in the template. Clear the stored data in that branch so stale content is not shown.