It’s a common practice that we call apex server-side controllers in lightning components. When you do so, it’s also important that you handle exception and throw the error properly to the client. By doing so, you can display error messages at client-side, rather than ending up debugging and figuring out what happened to the application.
How to achieve this? Well then let me introduce to you, AuraHandledException.
By throwing AuraHandledException, you can handle exception sensibly at client-side and display either the actual error message, or custom error message. How cool is that!!!
Let’s take an example here where we are have an app to create Account. The app will contain a button by clicking of which will create an Account. Now since our intention here is to show how we display error in client-side, let’s try creating an account without entering any details.
So to begin, let’s create a lightning component named AuraHandledExceptionDemo.cmp. The component will have a button to create an account. My intention here is to show exception messages, hence we are not going to accept any input to create account.
On button click, the component will call a controller method from AuraHandledExceptionDemoController.cmp, which in turn will call a method from AuraHandledExceptionDemoHelper.cmp as show below:
Now if you check AuraHandledExceptionHandler.cmp carefully, you can see that the helper method is calling an apex controller method called createAccount. Let’s see the apex controller AuraHandledExceptionDemoCntrl.
The above method createAccount() will create an account. If the account is created successfully it will return a string saying ‘Account Created’, else it will throw an exception. Now since we are calling this method from lightning component, and to ensure that the exception is caught at client-side, we are throwing an AuraHandledException here. In the current scenario since we are trying to create an account without any values passed, the method will definitly fail to create one and will throw an exception (thanks to try catch block).
Now let’s go back to AuraHandledExceptionDemoHelper.cmp and see how the error is caught. While checking for the state of the action callback, if it fails, then we are storing the error thrown by calling response.getError() function into a variable and then we are displaying the error message on the main component.
Now let’s create a lightning application called AuraHandledExceptionDemoApp and call this component in it.
Now let’s click preview and check what our application does.
As you can see, when we clicked Create Account button, it displayed an error message below the button, which says that the required fields are missing.
Hope this explains how to handle exceptions in Lightning components. If you have any questions, please feel free to post it on comments section.
For now, ADIOS!!!!