Development questions
How do you handle errors when calling Apex from LWC and display them to the user?
DevelopmentMedium
Server side: throw an AuraHandledException so the client gets a clean message.
apex
@AuraEnabled
public static void saveData(Account a) {
try { insert a; }
catch (DmlException e) { throw new AuraHandledException(e.getMessage()); }
}
Client side: the error object has shape error.body.message (or error.body as an array / pageErrors), so normalise it:
javascript
saveData({ a: this.acc })
.then(() => this.toast('Saved','success'))
.catch(e => this.toast('Error', 'error', e.body?.message));
For wire, check the { data, error } result. Also use errorCallback for unexpected rendering errors and lightning-record-edit-form onerror for LDS forms.
lwcerror-handlingapex
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?