Sub topic 7
Throwing useful errors from Apex
This chapter covers what happens when an Apex method called from a component fails, and how to make the message that reaches the user useful. It assumes you can already call an Apex method imperatively with async/await and know basic Apex exception handling (try/catch, custom exception classes). The next chapter covers how the component displays the error.
Why plain exceptions are not enough
Any uncaught exception in an @AuraEnabled method rejects the Promise on the client. The message the component receives depends on the exception type:
AuraHandledException: The message you set reaches the component aserror.body.message.- Other exceptions (
DmlException,QueryException, custom exceptions): In most orgs the component gets a generic message such as "An internal server error has occurred". Details appear only when debug mode is on.
This is deliberate. The platform does not expose stack traces or internal details to browsers by default. The cost is that users see unhelpful text unless you convert the error yourself.
| Thrown from Apex | What the component usually receives |
|---|---|
| `AuraHandledException` with a message set | Your message in `error.body.message` |
| `DmlException` left uncaught | A generic server error message |
| Custom exception left uncaught | A generic server error message |
| `AuraHandledException` with no message set | The text "Script-thrown exception" |
The Script-thrown exception gotcha
The constructor new AuraHandledException('text') does not make getMessage() return text. In Apex, getMessage() on this class returns "Script-thrown exception" unless you call setMessage(). The client may show your text, but Apex unit tests that assert on getMessage() will fail, and logs will be misleading.
The reliable pattern is a small factory method that sets both:
private static AuraHandledException newAuraException(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}Use it everywhere you throw to the client. Then the message is the same on the client, in getMessage(), and in tests.
A controller that throws useful errors
The next example validates input, converts DML failures into readable messages, and hides unexpected errors behind a safe message while logging the real cause.
public with sharing class ContactService {
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
if (String.isBlank(email)) {
throw newAuraException('Enter an email address.');
}
try {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (DmlException e) {
throw newAuraException(e.getDmlMessage(0));
} catch (Exception e) {
System.debug(
LoggingLevel.ERROR,
e.getTypeName() + ': ' + e.getMessage() + '\n' + e.getStackTraceString()
);
throw newAuraException(
'The contact could not be updated. Contact your administrator if this continues.'
);
}
}
private static AuraHandledException newAuraException(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}
}Three decisions are worth noting:
- Validation happens before the
tryblock. The blank-email check throws anAuraHandledExceptiondirectly, so the genericcatch (Exception e)cannot swallow it and replace the message. getDmlMessage(0)returns only the first failure's message. For a single-record update this is usually what you want. It is the text of a validation rule or a required-field error, which administrators write for users.- The final catch hides internals. Messages from unexpected exceptions can contain object names, field API names, or query text. Log them on the server and give the user a safe sentence.
Where errors come from
Choosing what to put in the message
A good message tells the user what happened and, when possible, what to do. A bad message exposes implementation details or says nothing.
- Prefer: "Enter an email address."
- Prefer: The text of a validation rule, such as "Email domain is not allowed."
- Avoid: "List has no rows for assignment to SObject."
- Avoid: "Attempt to de-reference a null object."
- Avoid: A message that includes record IDs, SOQL text, or field API names the user has no access to.
Messages from AuraHandledException are plain text. Do not build HTML into them, and do not rely on the component rendering markup.
Exceptions you create yourself
When you need to distinguish failure types inside Apex, define a custom exception and convert it at the boundary. This keeps your service logic independent of the Lightning layer and makes it reusable from batch jobs or triggers.
public with sharing class EmailPolicy {
public class PolicyException extends Exception {}
public static void check(String email) {
if (email != null && email.endsWith('@blocked.example')) {
throw new PolicyException('Addresses at blocked.example are not allowed.');
}
}
}The @AuraEnabled method then catches EmailPolicy.PolicyException and rethrows through newAuraException(e.getMessage()). Only the controller knows about AuraHandledException.
try {
EmailPolicy.check(email);
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (EmailPolicy.PolicyException e) {
throw newAuraException(e.getMessage());
}You can also write catch (EmailPolicy.PolicyException e) as one of several catch blocks, ahead of the generic catch (Exception e). Apex checks catch blocks in order, so put specific types first.
Security and access errors
Methods that use WITH USER_MODE or as user enforce the running user's object and field permissions. When a user lacks access, the platform throws an exception instead of silently returning less data. The exact type varies by operation, so handle it through your generic catch rather than assuming one class. Two practical points follow:
- Do not tell the user which field or object they lack access to unless that is helpful and not sensitive. "You do not have permission to update this contact." is usually enough.
- Log the original exception, as in the
ContactServiceexample, so an administrator can diagnose it.
Reading the error on the client
On the client, the catch block receives an object whose shape depends on the source of the error. For AuraHandledException it is error.body.message. Network failures and some framework errors have no body, and other callers can return an array in body. A small defensive helper keeps components consistent:
export function reduceError(error) {
if (!error) {
return 'Unknown error';
}
if (Array.isArray(error.body)) {
return error.body.map((e) => e.message).join(', ');
}
if (typeof error.body?.message === 'string') {
return error.body.message;
}
if (typeof error.message === 'string') {
return error.message;
}
return 'Unknown error';
}Using it in the component from earlier chapters:
import { LightningElement } from 'lwc';
import updateEmail from '@salesforce/apex/ContactService.updateEmail';
import { reduceError } from 'c/errorUtils';
export default class ContactEmailEditor extends LightningElement {
contactId;
email = '';
errorMessage;
async handleSave() {
this.errorMessage = undefined;
try {
await updateEmail({ contactId: this.contactId, email: this.email });
} catch (error) {
this.errorMessage = reduceError(error);
}
}
}The helper lives in its own module, c/errorUtils, so every component can import it. How to display the message is the subject of the next chapter.
Testing the error path in Apex
Test that your method throws the message you intend, not only that it throws. This is where the setMessage() call pays off.
@IsTest
private class ContactServiceTest {
@IsTest
static void blankEmailIsRejectedWithReadableMessage() {
try {
ContactService.updateEmail(null, '');
Assert.fail('Expected an AuraHandledException');
} catch (AuraHandledException e) {
Assert.areEqual('Enter an email address.', e.getMessage());
}
}
}Assert.fail throws an AssertException. The catch (AuraHandledException e) block does not catch that, so the test fails if no exception was thrown.
Common mistakes
- Forgetting
setMessage(). The client may look right while Apex tests assert on "Script-thrown exception". - Catching your own exception. A
throwinside atryblock with a trailingcatch (Exception e)gets caught and replaced by the generic message. - Throwing a custom exception straight to the client. The component gets a generic error.
- Exposing internals. Do not return
e.getMessage()from an unexpected exception. Log it instead. - Swallowing the error. A
catchthat returnsnullmakes the component think the call succeeded.
Exercise
A controller method contains throw new AuraHandledException('Email is required'); inside a try block that is followed by catch (Exception e) { throw new AuraHandledException('Something went wrong'); }. The user sees "Something went wrong". Why, and how do you fix it? Also, what will e.getMessage() return in an Apex test that catches the first exception, and how do you change that?
Show answer
The first AuraHandledException is thrown inside the try block, so the generic catch (Exception e) catches it and the code throws a new one with the vague message. Fix it by moving the validation before the try block, or by adding a catch for AuraHandledException above the generic catch that rethrows it. In a test, getMessage() returns "Script-thrown exception" because the constructor argument does not set the Apex message. Call setMessage() with the same text before throwing, for example through a newAuraException helper.