Sub topic 8
Throwing and displaying errors
This chapter assumes you can write basic Apex with try/catch, and that you have built a Lightning web component that calls an @AuraEnabled method with @wire or imperatively.
Why errors need special handling
An exception thrown in an @AuraEnabled method travels back to the browser as a failed call. Two things matter:
- The component only receives a useful message if you throw an
AuraHandledExceptionwith that message. - Other exception types reach the client with little usable detail, and you may leak internal information.
So the pattern is to catch what you expect, then rethrow an AuraHandledException that carries a message safe for users to read.
Throwing the exception in Apex
The method below catches a DmlException and converts it.
public with sharing class ContactController {
@AuraEnabled
public static Contact createContact(String lastName, Id accountId) {
try {
Contact c = new Contact(LastName = lastName, AccountId = accountId);
insert as user c;
return c;
} catch (DmlException e) {
throw new AuraHandledException('Could not create the contact: ' + e.getMessage());
}
}
}Catch the narrowest exception type you can. A broad catch (Exception e) hides programming mistakes behind a friendly message.
Showing the error in an imperative call
An imperative call returns a promise. When Apex throws, the promise rejects and the error object carries the message in error.body.message.
import { LightningElement, api } from 'lwc';
import createContact from '@salesforce/apex/ContactController.createContact';
export default class ContactCreator extends LightningElement {
@api recordId;
lastName = '';
error;
handleChange(event) {
this.lastName = event.target.value;
}
async handleSave() {
try {
const contact = await createContact({
lastName: this.lastName,
accountId: this.recordId
});
this.error = undefined;
console.log('Created contact', contact.Id);
} catch (error) {
this.error = error.body ? error.body.message : error.message;
}
}
}The check error.body ? matters. Server errors have a body. Errors raised in your own JavaScript, such as a TypeError, do not, and they use error.message instead.
Showing the error from @wire
A wired property is an object with data and error fields. When the call fails, error holds the same structure as an imperative rejection.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
get errorMessage() {
const error = this.contacts.error;
if (!error) {
return undefined;
}
return error.body ? error.body.message : error.message;
}
}In the template, render errorMessage with lwc:if={errorMessage} so the message appears only when a call has failed.
Controlling the message text
A known gotcha: when you build an AuraHandledException with a message in its constructor, getMessage() on that exception can return the generic text "Script-thrown exception". This affects Apex code that reads the message back, such as tests. The client still receives your message. To make getMessage() return your text as well, call setMessage.
public with sharing class ErrorHelper {
public static AuraHandledException build(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}
}Then write throw ErrorHelper.build('Could not create the contact.');.
Common mistakes
| Mistake | Result |
|---|---|
| Throwing a custom exception without converting it | The component gets little useful detail |
| Reading `error.message` for server errors | The value is undefined, because the text is in `error.body.message` |
| Swallowing the exception and returning null | The component shows nothing and the user cannot tell the save failed |
| Not checking `error.body` | A JavaScript error causes a second failure inside the catch block |
Exercise
A component calls an Apex method imperatively. The method throws new AuraHandledException('Name is required'), but the component displays "undefined" when it reads error.message. What is wrong, and how do you fix it?
Show answer
Server errors place the text in error.body.message, not error.message. Change the catch block to this.error = error.body ? error.body.message : error.message;. The body check also covers client-side errors that have no body.