Throwing Custom Error Message from Apex to your Lightning or LWC component is quite easy and standard. While saving a record, you never know what exception may occur. It may be a Validation rule exception or Required Field Exception or any other Apex Exception. With Aura Handled Exception, you can throw these exceptions right on the screen and can show them in Toast Messages.
To throw the multiple Custom Exceptions from Apex, first, create a Custom Exception class.
1 2 3 4 5 |
public class MyException extends Exception { } |
Now, you can refer to the below code to throw custom exceptions. Since we are using try-catch block here, any standard exception if occurred will also be thrown to UI.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class CustomError { public static void saveRecords(String recordId) { try { if(String.isNotBlank(recordId)) { List<Account> accounts = [SELECT id, Name FROM Account WHERE id =: recordId]; if(accounts != null && accounts.size() > 0) { // Do Some Action } else { throw new MyException('Record Id is Invalid'); } } else { throw new MyException('Record Id is Blank'); } } catch(Exception ex) { if ( String.isNotBlank( ex.getMessage() ) && ex.getMessage().contains( 'error:' ) ) { throw new AuraHandledException(ex.getMessage().split('error:')[1].split(':')[0] + '.'); } else { throw new AuraHandledException(ex.getMessage()); } } } } |
Now on Lightning, you can refer to the below code to show errors.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
({ doInitHelper: function (component, helper) { var recordId = component.get('v.recordId'); if (!$A.util.isEmpty(recordId)) { var action = component.get("c.saveRecords"); action.setParams({ recordId: recordId }); action.setCallback(this, function (response) { var result = response.getReturnValue(); if (response.getState() === "SUCCESS") { } else { var errors = response.getError(); if (Array.isArray(errors) && errors.length && errors[0] && errors[0].message) { helper.showToast('Error', errors[0].message); } } }); $A.enqueueAction(action); } }, showToast: function (type, message) { $A.get('e.force:showToast').setParams({ title: type, message: message, type: type.toLowerCase() }).fire(); } }) |
So, in this way you can show Custom Error Message on Lightning UI. With this method, you can throw your custom message as well as standard will be thrown automatically.
If you want to throw only a single custom message, you can directly throw it from auraHandledException only.
1 2 3 |
throw new AuraHandledException('Your Custom Message Here'); |
To refer to the Salesforce documentation, Click Here
Also Check:
For any queries or suggestions, comment below.
Cheers … Happy Coding … 🙂