Sub topic 13
Returning errors to Lightning components
This chapter assumes you can write try/catch blocks, define custom exceptions, and handle DmlException, as covered in earlier chapters. It also assumes you know what an @AuraEnabled method is. Here you will see what a Lightning component receives when Apex fails, and how to make that message useful.
What the browser sees when Apex fails
An @AuraEnabled method runs on the server, and the component calls it from the browser. If the method throws an exception, the transaction rolls back as usual, and the framework sends an error response to the client. The client then runs the error path of the call: the catch of a promise, or the error property of a wire result.
The message the client receives depends on the exception type:
| Exception thrown from the method | What the component gets |
|---|---|
| `DmlException`, `QueryException`, custom exception, or any other type | A generic message, such as "Script-thrown exception". The real details stay on the server. |
| `AuraHandledException` | The message you supplied, in `error.body.message`. |
The framework hides details of ordinary exceptions on purpose, because they can expose object names, field names, or stack traces to users. AuraHandledException is how you opt in to showing a specific message. You decide what the user is allowed to read.
The diagram shows the path of an error.
Throwing AuraHandledException
This controller catches the DmlException and rethrows it as an AuraHandledException:
public with sharing class AccountController {
@AuraEnabled
public static void saveAccount(Account acc) {
try {
insert acc;
} catch (DmlException e) {
AuraHandledException ex = new AuraHandledException(e.getMessage());
ex.setMessage(e.getMessage());
throw ex;
}
}
}The two lines that use the message look redundant, but both are needed. The constructor argument is what the client receives. In Apex code, though, getMessage() on an AuraHandledException returns "Script-thrown exception" unless you call setMessage. This matters in unit tests and in any Apex code that catches the exception. Calling both makes the client and the server agree on the text.
Why not just let the DmlException propagate?
If you leave the DmlException uncaught, the component shows a generic error and the user cannot tell what went wrong. Converting it gives them text to act on. Note that e.getMessage() for a DML failure is long and technical. It looks like this:
Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Name]: [Name]That message is accurate, but it is not friendly. The next section shows how to build something better.
Writing messages for users
DmlException gives you per-record detail through getDmlMessage(index). This version returns only the human-readable part and logs the full exception for developers:
public with sharing class AccountController {
@AuraEnabled
public static void saveAccount(Account acc) {
try {
insert acc;
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, e.getStackTraceString());
throw buildAuraException(e.getDmlMessage(0));
}
}
private static AuraHandledException buildAuraException(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}
}The helper removes the two-step pattern from every method. getDmlMessage(0) returns just the error text, such as "Required fields are missing: [Name]", without the "Insert failed. First exception on row 0" prefix.
The service layer should not know about the UI. Let services throw their own custom exceptions, and convert them to AuraHandledException only in the controller. The controller below handles two cases:
public with sharing class InvoiceController {
@AuraEnabled
public static Decimal discountedTotal(Decimal amount, Decimal percent) {
try {
return InvoiceService.applyDiscount(amount, percent);
} catch (InvoiceService.InvoiceException e) {
// The message was written for users, so pass it through.
throw buildAuraException(e.getMessage());
} catch (Exception e) {
// Unknown failure: log the details, show a safe message.
System.debug(LoggingLevel.ERROR, e.getTypeName() + ': ' + e.getMessage());
throw buildAuraException('Something went wrong. Contact your administrator.');
}
}
private static AuraHandledException buildAuraException(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}
}This uses the catch-order rule from the earlier chapter: the specific exception comes first, and Exception last. It uses InvoiceService from the chapter on custom exceptions.
Only pass messages through when you wrote them for users. Messages from QueryException, NullPointerException, and similar types can mention internals. For those, use a fixed text and log the details.
Handling the error in the component
On the client, the error is an object. The text is in error.body.message. This Lightning Web Component calls the controller imperatively and shows the message:
import { LightningElement } from 'lwc';
import saveAccount from '@salesforce/apex/AccountController.saveAccount';
export default class AccountForm extends LightningElement {
name = '';
errorMessage = '';
handleNameChange(event) {
this.name = event.target.value;
}
async handleSave() {
this.errorMessage = '';
try {
await saveAccount({ acc: { Name: this.name } });
} catch (error) {
this.errorMessage = error.body ? error.body.message : error.message;
}
}
}The error.body ? ... : ... check matters. Not every failure comes from Apex. A network drop or a session timeout produces an error without a body, and reading error.body.message would then throw a second error inside your handler.
The matching template displays the message when one is set:
<template>
<lightning-input label="Account name" value={name} onchange={handleNameChange}></lightning-input>
<lightning-button label="Save" onclick={handleSave}></lightning-button>
<template lwc:if={errorMessage}>
<p class="slds-text-color_error">{errorMessage}</p>
</template>
</template>With @wire, the same object arrives in the error property of the wired result, and the message is again in error.body.message. A cacheable method (@AuraEnabled(cacheable=true)) can throw AuraHandledException in the same way.
Testing the controller
A test should confirm both that the exception is thrown and that its message is readable. This is where setMessage pays off:
@IsTest
private class AccountControllerTest {
@IsTest
static void returnsReadableMessageForMissingName() {
try {
AccountController.saveAccount(new Account());
Assert.fail('Expected AuraHandledException was not thrown');
} catch (AuraHandledException e) {
Assert.isTrue(
e.getMessage().contains('Required fields are missing'),
'Unexpected message: ' + e.getMessage()
);
}
}
}If you remove setMessage, e.getMessage() returns "Script-thrown exception" and the assertion fails, even though the browser would have received the right text. Assert.fail throws an AssertException, which the AuraHandledException catch block does not match, so the test fails when no exception occurs.
Common mistakes
- Forgetting
setMessage. The client works, but tests and server-side logs show "Script-thrown exception". - Throwing
AuraHandledExceptionfrom deep in a service class. This ties business logic to the UI layer. Throw a custom exception there and convert it in the controller. - Passing every message through. Raw exception messages can reveal field API names and record IDs. Pass through only messages you wrote for users.
- Swallowing the exception. A
catchblock that logs and returns normally tells the component the call succeeded. Always rethrow something the client can see. - Assuming
error.bodyexists. Check for it, as shown above.
Exercise
A Lightning component calls an Apex method that throws a custom InvoiceException. The component shows only a generic message. In a unit test for the controller, e.getMessage() on a caught AuraHandledException returns "Script-thrown exception". Name the two fixes, one for each problem.
Show answer
For the component, catch InvoiceException in the @AuraEnabled method and throw an AuraHandledException carrying the message, because the framework hides the messages of other exception types. For the test, call setMessage on the AuraHandledException with the same text, because without it getMessage() returns "Script-thrown exception" in Apex.
Exercise
Why should error.body.message in a component's catch handler be guarded with a check that error.body exists?
Show answer
Errors that do not come from Apex, such as a network failure, have no body property. Reading error.body.message on them throws a second error inside the handler, so the user sees nothing useful.