Sub topic 3
Throwing and Displaying Errors in Apex Controllers
Assume you know basic Apex, SOQL, DML, Lightning Web Components (LWC), and Salesforce record IDs. This chapter focuses on controller failures, security, cache refreshes, and tests.
Throwing and displaying errors
Use AuraHandledException when a controller needs to send a safe, readable message to a component. Catch expected database errors and avoid exposing internal details unnecessarily.
public with sharing class ContactController {
@AuraEnabled
public static Contact createContact(String lastName, Id accountId) {
try {
Contact contact = new Contact(
LastName = lastName,
AccountId = accountId
);
insert as user contact;
return contact;
} catch (DmlException error) {
throw new AuraHandledException(
'The contact could not be created.'
);
}
}
}An imperative LWC call returns a promise. Read the server message from error.body.message.
async handleSave() {
try {
await createContact({
lastName: this.lastName,
accountId: this.recordId
});
this.error = undefined;
} catch (error) {
this.error = error.body?.message || 'Unexpected server error.';
}
}Enforcing sharing and permissions
with sharing applies record-sharing rules to the class. It does not automatically enforce object-level or field-level permissions. Use user-mode SOQL and DML when the operation should follow the running user’s permissions.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}Refreshing cached results
A wired, cacheable method can return cached data. After a successful write, call refreshApex with the complete wired property.
import { refreshApex } from '@salesforce/apex';
async handleRefresh() {
await refreshApex(this.contacts);
}The write and refresh are separate operations. Refresh only after the write succeeds.
Writing tests for controller methods
Create test records, call the method inside Test.startTest() and Test.stopTest(), and assert both success and failure paths.
@IsTest
private class ContactControllerTest {
@IsTest
static void rejectsMissingLastName() {
Account account = new Account(Name = 'Test Account');
insert account;
try {
ContactController.createContact('', account.Id);
Assert.fail('Expected an exception');
} catch (AuraHandledException error) {
Assert.isTrue(error.getMessage().contains('could not be created'));
}
}
}Choosing Apex or Lightning Data Service
Use Lightning Data Service (LDS) for standard record loading, editing, caching, and sharing behavior. Use Apex when you need custom SOQL, joins across objects, complex business rules, or a transaction involving several operations.
Calling Apex from Aura components
Aura components call the same @AuraEnabled method through an action.
var action = component.get("c.getContacts");
action.setParams({ accountId: component.get("v.recordId") });
action.setCallback(this, function(response) {
if (response.getState() === "SUCCESS") {
component.set("v.contacts", response.getReturnValue());
} else {
component.set("v.error", "Could not load contacts.");
}
});
$A.enqueueAction(action);Exercise
Why should a cacheable wired result be refreshed after a successful Apex write?
Show answer
The client may still hold the older cached result, so refreshApex asks the server for current data.