Sub topic 7
Throwing useful errors from Apex
This chapter assumes you can write an @AuraEnabled method and call it from a component with await. It covers what the browser receives when the Apex method fails, and how to make that message useful.
What the component receives by default
If an Apex method throws an unhandled exception, the Promise in your component rejects. In production, the message is usually generic, such as "An internal server error has occurred" with an error ID. This is deliberate. Salesforce hides stack traces and internal details from client code.
You can't fix this by catching the error in JavaScript, because the detail never leaves the server. You have to decide in Apex which messages the user may see.
Throwing AuraHandledException
AuraHandledException is the exception type that carries a message to the client. Catch the exceptions you expect, then rethrow one of these with text a user can act on.
There is a known gotcha. If you pass a message only to the constructor, getMessage() on the server can return "Script-thrown exception". This shows up in Apex tests and in logs. Calling setMessage with the same text fixes it. A small helper keeps this in one place.
public with sharing class ContactController {
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
if (String.isBlank(email)) {
throw buildError('Enter an email address before saving.');
}
try {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (DmlException e) {
throw buildError(e.getDmlMessage(0));
}
}
private static AuraHandledException buildError(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}
}Two choices in this code matter:
- Validate early. The blank-email check gives a clear message without a database round trip.
- Use
getDmlMessage(0). It returns the message for the first failed record, such as a validation rule message.e.getMessage()would add system text around it.
Choosing what to expose
Show messages that help the user fix the problem. Don't expose messages that reveal internals.
| Situation | What to throw |
|---|---|
| Missing or invalid input | `AuraHandledException` with a plain instruction |
| Validation rule or required field failure | `AuraHandledException` with `getDmlMessage(0)` |
| Unexpected error (null reference, limits) | Log it, then throw a generic `AuraHandledException` |
try {
// work that might fail unexpectedly
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, e.getMessage() + '\n' + e.getStackTraceString());
throw buildError('Something went wrong while saving. Try again or contact your administrator.');
}Put this generic catch after the specific ones, so that the specific messages still reach the user.
Reading the message in JavaScript
The rejected value is an object, and the Apex message sits at error.body.message. The handler in the component should read it defensively, because network failures and other errors have a different shape.
try {
await updateEmail({ contactId: this.recordId, email: this.email });
} catch (error) {
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}The error?.message fallback covers errors that never came from Apex. The next chapter builds on this and covers displaying errors in the component.
Exercise
A user saves a contact and the component shows "Script-thrown exception" in your Apex test, while the real text is a validation rule message. What two changes make the correct message appear?
Show answer
Catch the DmlException and rethrow an AuraHandledException built from e.getDmlMessage(0). Then call setMessage on the AuraHandledException with the same text, so getMessage() returns it instead of "Script-thrown exception".
Exercise
In the component's catch block, which property holds the message thrown from Apex, and why add a fallback to error.message?
Show answer
The message is in error.body.message. The fallback is needed because errors that don't come from Apex, such as a network failure, have no body, so the optional chaining would otherwise leave you with no message to show.