Sub topic 6
Handling permission failures
User mode operations fail loudly when the running user lacks access. This chapter covers what the failures look like, how to catch them, and how to turn them into useful messages without hiding real problems. It assumes you can write Apex classes, use try/catch, and run SOQL and DML. It also assumes you know what object permissions (CRUD) and field-level security (FLS) are, and that you have seen WITH USER_MODE and as user in the previous chapters.
What a failure looks like
In system mode, a query for a field the user cannot read succeeds. User mode changes that. The platform checks the user's access before it runs the operation, and it stops the operation when a check fails. Nothing is returned and nothing is saved silently.
The failure type depends on the operation.
| Operation | How it fails | What you handle |
|---|---|---|
| Static SOQL with `WITH USER_MODE` | Throws `QueryException` | try/catch around the query |
| Dynamic SOQL with `AccessLevel.USER_MODE` | Throws `QueryException` | try/catch around the call |
| DML with `as user` | Throws `DmlException` | try/catch around the statement |
| `Database.insert` and similar with `allOrNone` set to `false` | Returns a result per record | Loop over the results and check `isSuccess()` |
The last row needs care. The allOrNone flag controls what happens when a record fails. It does not turn every permission problem into a per-record error. Treat the two paths as separate: a thrown exception means the whole call was rejected, and a failed result means one record was rejected. If you use the Database methods with false, handle both. Which problems surface as which can depend on the kind of check that failed and on the API version. Test the cases that matter to you in your own org instead of relying on message text.
Catching query failures
A user mode query throws QueryException when the user cannot access the object, or cannot read a field the query references. That includes fields used only in WHERE or ORDER BY, not just those in the select list.
A basic handler catches the exception, logs the technical detail, and throws a message that is safe to show:
public with sharing class AccountReader {
public static List<Account> readAccounts() {
try {
return [SELECT Id, Name, Industry FROM Account WITH USER_MODE LIMIT 50];
} catch (QueryException e) {
System.debug(LoggingLevel.WARN, 'Account read denied: ' + e.getMessage());
AuraHandledException ex = new AuraHandledException('You do not have access to this data.');
ex.setMessage('You do not have access to this data.');
throw ex;
}
}
}Why `setMessage` is there
Code called from Lightning Web Components or Aura usually throws AuraHandledException. If you only pass the text to the constructor, the client often receives the generic text "Script-thrown exception" instead of your message. Calling setMessage with the same text fixes this, and it also makes getMessage() return your text in unit tests. The code above uses both calls on purpose.
Keep the catch narrow
QueryException is not only a permissions error. It is also thrown for a malformed dynamic query, and when a query returns no rows for a single-record assignment such as Account a = [SELECT Id FROM Account WHERE Id = :id];. If you catch it and always report "no access", you will mislead users and hide bugs. Two habits reduce this:
- Wrap only the query, not a whole method body.
- Log
e.getMessage()ande.getTypeName()so a developer can tell a permission failure from a bad query.
Catching DML failures
For a single statement with as user, catch DmlException:
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, 'Contact insert failed: ' + e.getMessage());
AuraHandledException ex = new AuraHandledException('The contact could not be saved.');
ex.setMessage('The contact could not be saved.');
throw ex;
}
}
}DmlException is also thrown for validation rule failures, required fields, and duplicate rules. The same narrow-catch advice applies. Use e.getDmlType(0) or e.getDmlFields(0) when you need to know what went wrong for the first failing row.
Per-record errors with partial success
When you pass false for allOrNone, the call returns a Database.SaveResult for each record, in the same order as the input list. The loop below reports a count of saved rows and one line per failure:
public with sharing class ContactImportService {
public class ImportResult {
public Integer created = 0;
public List<String> errors = new List<String>();
}
public static ImportResult importContacts(List<Contact> contacts) {
ImportResult result = new ImportResult();
List<Database.SaveResult> saves;
try {
saves = Database.insert(contacts, false, AccessLevel.USER_MODE);
} catch (DmlException e) {
// The whole call was rejected, so no per-record results exist.
result.errors.add('Import blocked: ' + e.getMessage());
return result;
}
for (Integer i = 0; i < saves.size(); i++) {
if (saves[i].isSuccess()) {
result.created++;
continue;
}
for (Database.Error err : saves[i].getErrors()) {
String fields = err.getFields().isEmpty()
? 'n/a'
: String.join(err.getFields(), ', ');
result.errors.add(
'Row ' + i + ' [' + err.getStatusCode() + '] '
+ err.getMessage() + ' (fields: ' + fields + ')'
);
}
}
return result;
}
}Points to notice:
- The
trycovers the wholeDatabase.insertcall because it can still throw even withallOrNoneset tofalse. - Results line up with the input by index. Use the index to tell the user which row failed.
err.getStatusCode()returns aStatusCodeenum value. Compare against the enum if you need to branch on a specific cause, and avoid parsing the message text.err.getFields()can be empty, so check before joining.
Transactions and partial work
A thrown exception that nobody catches ends the transaction and rolls back every change made in it. Catching the exception changes this. After a catch, any DML that ran earlier in the same transaction stays and will commit when the transaction finishes.
Say a method inserts an Account with as user and then inserts a Contact the user cannot create. If you catch the Contact failure and carry on, the Account is still saved. Use a savepoint when the steps belong together:
public with sharing class OnboardingService {
public static void createAccountWithContact(String accountName, String lastName) {
Savepoint sp = Database.setSavepoint();
try {
Account a = new Account(Name = accountName);
insert as user a;
Contact c = new Contact(LastName = lastName, AccountId = a.Id);
insert as user c;
} catch (DmlException e) {
Database.rollback(sp);
System.debug(LoggingLevel.WARN, 'Onboarding rolled back: ' + e.getMessage());
AuraHandledException ex = new AuraHandledException('Onboarding could not be completed.');
ex.setMessage('Onboarding could not be completed.');
throw ex;
}
}
}Rolling back with a savepoint resets the records' Ids you created in the transaction, so do not reuse a after the rollback.
Choosing between failing and degrading
User mode fails the whole operation. Sometimes that is wrong for the screen you are building. A related list might be fine without one restricted column. In that case you have two options:
- Query only the fields the user can see. This needs a describe check before building the field list, which the later chapter on older approaches covers.
- Use
Security.stripInaccessibleon the result, which removes unreadable fields instead of throwing. It suits partial display, but the user is not told anything was removed.
For writes, prefer failing. Silently dropping a field the user could not edit makes data look saved when it is not. A user mode error is the safer default for DML.
Common mistakes
- Catching
Exceptioneverywhere. It also swallowsLimitException-style problems that cannot be caught anyway, and it hides programming errors. Catch the specific type. - Showing
e.getMessage()to end users. The text can name objects and fields the user is not allowed to know about. Log it, and show a general message. - Skipping
setMessageonAuraHandledException. The component then shows a generic error and you lose the explanation. - Ignoring the result list. With
allOrNoneset tofalse, a loop that never checksisSuccess()reports success when rows failed. - Assuming the empty result means no access. A user mode query on an object the user can read, with sharing hiding every record, returns an empty list and no exception. Absence of an error does not tell you the user could see everything.
- Testing only the happy path. If the permission failure branch has never run, you do not know it works. The testing chapter covers
System.runAs, and the exercise below previews the idea.
Summary of the pattern
A reliable handler follows the same order each time. Run the operation in user mode, and catch the specific exception around that operation only. Log the technical detail for developers, and throw or return a short message for the user. Roll back with a savepoint when later steps depend on earlier ones. When you use partial success, check every result.
Exercise
A method inserts 200 contacts with Database.insert(contacts, false, AccessLevel.USER_MODE) inside a try/catch for DmlException. The user can create Contacts but cannot edit the Email field. The method returns without error and reports "200 contacts imported". Which mistake in the handling would let this report be wrong, and how do you fix it?
Show answer
The code does not check the returned Database.SaveResult list. With allOrNone set to false, rows can fail without an exception, so the method must loop over the results and count only those where isSuccess() is true. For each failure it should collect getErrors() (status code, message, and fields) and return them, so the message says how many rows were imported and which ones failed. The try/catch is still needed for the case where the whole call is rejected.
Exercise
A method inserts an Account with insert as user, then inserts a Contact with insert as user inside a try/catch that only logs the DmlException. The user cannot create Contacts. What data ends up in the database, and what change makes the two inserts succeed or fail together?
Show answer
The Account is saved, because the exception was caught and the transaction commits with the earlier DML. To make both inserts succeed or fail together, call Database.setSavepoint() before the first insert and Database.rollback(sp) in the catch block, then rethrow a user-friendly exception.