Sub topic 6
Handling permission failures
This chapter assumes you can write basic Apex classes, run SOQL and DML, and know what object permissions (CRUD) and field-level security (FLS) are. You should also have seen WITH USER_MODE and as user in the previous chapters.
User mode checks permissions at run time. If the running user lacks access, the operation fails instead of quietly returning less data. Your code needs a plan for that failure.
What fails and how
The failure type depends on the operation.
| Operation | Failure | Exception or result |
|---|---|---|
| Static or dynamic SOQL in user mode | User cannot read the object or a referenced field | `QueryException` |
| `insert as user`, `update as user`, and similar | User cannot create or edit the object or field | `DmlException` |
| `Database.insert(records, false, AccessLevel.USER_MODE)` | Same permission problem, with partial success | No exception. Errors are in each `Database.SaveResult` |
Permission checks cover more than the SELECT list. A field used in WHERE or ORDER BY must also be readable, or the query fails.
Catching a query failure
Catch QueryException where you can turn the failure into something useful. In an Aura or LWC controller, AuraHandledException carries a message to the browser.
public with sharing class AccountReader {
public static List<Account> safeRead() {
try {
return [SELECT Id, Name FROM Account WITH USER_MODE];
} catch (QueryException e) {
// The user lacks access to Account or to a referenced field.
System.debug(LoggingLevel.WARN, 'Access denied: ' + e.getMessage());
throw new AuraHandledException('You do not have access to this data.');
}
}
}The log line keeps the technical detail for administrators. The user sees a short message that does not reveal field names or internal structure.
Handling DML failures
A single insert as user throws a DmlException when the user lacks permission. Catch it the same way:
public with sharing class ContactService {
public static void createContact(String lastName, String email) {
Contact c = new Contact(LastName = lastName, Email = email);
try {
insert as user c;
} catch (DmlException e) {
System.debug(LoggingLevel.WARN, 'Insert failed: ' + e.getMessage());
throw new AuraHandledException('You cannot create contacts.');
}
}
}When you pass false for allOrNone, the method does not throw for per-record problems. You must read the results yourself:
public with sharing class ContactBatchService {
public static List<String> createContacts(List<Contact> contacts) {
List<String> problems = new List<String>();
List<Database.SaveResult> results =
Database.insert(contacts, false, AccessLevel.USER_MODE);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
problems.add('Row ' + i + ': ' + err.getMessage());
}
}
}
return problems;
}
}Each Database.Error has a message and, for field problems, the affected field names through getFields(). Keep the row index so the caller can tell which record failed.
Choosing what to catch
Follow these rules to avoid hiding real problems:
- Catch the narrowest type.
QueryExceptionandDmlExceptionare enough here. CatchingExceptionalso swallows bugs such as null references. - Catch near the boundary that talks to the user, such as a controller. Lower layers should let the exception pass up.
- Do not retry in system mode after a failure. That defeats the check you added.
- Do not return an empty list as a "safe" fallback. The caller cannot tell "no records" from "no access".
When partial data is acceptable
Sometimes you want to show whatever the user can see. User mode is the wrong tool for that, because it fails on the first inaccessible field. Security.stripInaccessible removes those fields instead of throwing:
public with sharing class StripExample {
public static List<Account> readableOnly(List<Account> records) {
SObjectAccessDecision decision = Security.stripInaccessible(AccessType.READABLE, records);
return (List<Account>) decision.getRecords();
}
}Use this deliberately. A later chapter compares the approaches in detail.
Exercise
A trigger helper calls Database.update(accounts, false, AccessLevel.USER_MODE) for a user without edit access to the Industry field. The method returns normally and no exception is thrown. Why, and what should the code do?
Show answer
With allOrNone set to false, failures are reported per record in the returned Database.SaveResult list instead of as an exception. The code must loop over the results, check isSuccess(), and read getErrors() for each failed record. It can then report the failures to the caller.
Exercise
Why is returning an empty List<Account> from a catch (QueryException e) block a poor way to handle a permission failure?
Show answer
The caller cannot distinguish "the user has no matching records" from "the user is not allowed to read them". This hides the problem and makes bugs harder to find. Rethrow a meaningful exception, such as AuraHandledException, instead.