function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Manoj BadamManoj Badam 

custom exception in lightning component

I wanted to create a custom exception message and thought it to the lightning component .. Does its possible ?
Best Answer chosen by Manoj Badam
NagendraNagendra (Salesforce Developers) 
Hi Manoj,

Visualforce pages have built-in implementation for showing custom error messages using the page as a medium. Here, we can easily show custom error screens with different text and levels of severity (info/error/warning) regardless of the return type of the apex controller method.

With Lightning components, we don’t have the flexibility to use page messages, and this makes the process more difficult. We have to return an error message for an apex controller method of which the return type is anything other than string (e.g., an apex method that returns a list of sObject).

To show custom error messages in Lightning:
Return the custom error messages from apex method.
Show the error messages in the Component.
Returning the custom error messages from apex method:

The recommended approach is to create — and throw — a System.AuraHandledException from your server-side controller to return a custom error message.

This can be done using the following syntax:

In the apex controller class:
//If Account ID sent as parameter is null
string errAccId = ‘Account ID not available.’;
AuraHandledException ex = new AuraHandledException(errAccId);
ex.setMessage(errAccId);
throw ex;
Here setMessage() on exception object is important, in order to validate this scenario apply Test Class using the following syntax:
//To validate the scenario in test class
try {
     Controller.Method(”); //calling the controller method with account Id
} catch (AuraHandledException e) {
      System.assert(e.getMessage().contains(‘Account ID not available.’));
}
Showing the error messages in the Component.
To show the error message on the lightning component UI, we would use the following:


Generic reusable message component:
<aura:component access=”global”>
<aura:attribute name=”message” description=”Message content, can be HTML”
                   type=”String” default=”Message from MessageComponent.cmp”/>
<aura:attribute name=”type”
                   description=”Message type, can be error/warning/info/success”
                   type=”String” default=”info”/>
<div class=”{!’slds-box slds-theme–alert-texture slds-theme–‘ + v.type}”>
<lightning:icon iconName=”{! ‘utility:’+ v.type }” size=”medium”
                       alternativeText=”{!v.type}” Class=”iconContainer”/>&nbsp;
<span class=”slds-text-body–regular”>
<aura:unescapedHtml value=”{!v.message}”/>
</span>
</div>
</aura:component>
In the controller/helper:
action.setCallback(this, function(resp) {
if (resp.getState() === “SUCCESS”) {
     component.set(“v.messageType”, ‘success’ );
component.set(“v.message”, ‘Completed Successfully!’ );
}
else if (resp.getState() === “ERROR”) {
     component.set(“v.messageType”, ‘error’ );
var errors = resp.getError();
if (errors) {
if (errors[0] && errors[0].message) {
component.set(“v.message”,errors[0].message );//Fetching Custom Message.
        }
}
else {
component.set(“v.message”, ‘Request Failed!’ );
}
}
});
Using the message component in our component markup:
<c:MessageComponent type=”{!v.messageType}” message=”{!v.message}” />
Eg:
For error message would look like:
<c:MessageComponent type=”error” message=”Account Id Not available.” />
User-added imageSimilar to a warning message, information and success screens could look like:
User-added imageUser-added imageUser-added image
Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra
 

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Manoj,

Greetings to you!

Please refer to the below links which might help you further with the above requirement.

https://salesforce.stackexchange.com/questions/160160/show-custom-error-on-lightninginput

https://hub.appirio.com/tech-blog/custom-error-messages-in-salesforce-lightning

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/controllers_server_apex_custom_errors.htm

http://www.terrasky.com/how-to-handle-apex-errors-for-lightning-component-implementations/

https://webkul.com/blog/exception-handling-lightning-component/

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
NagendraNagendra (Salesforce Developers) 
Hi Manoj,

Visualforce pages have built-in implementation for showing custom error messages using the page as a medium. Here, we can easily show custom error screens with different text and levels of severity (info/error/warning) regardless of the return type of the apex controller method.

With Lightning components, we don’t have the flexibility to use page messages, and this makes the process more difficult. We have to return an error message for an apex controller method of which the return type is anything other than string (e.g., an apex method that returns a list of sObject).

To show custom error messages in Lightning:
Return the custom error messages from apex method.
Show the error messages in the Component.
Returning the custom error messages from apex method:

The recommended approach is to create — and throw — a System.AuraHandledException from your server-side controller to return a custom error message.

This can be done using the following syntax:

In the apex controller class:
//If Account ID sent as parameter is null
string errAccId = ‘Account ID not available.’;
AuraHandledException ex = new AuraHandledException(errAccId);
ex.setMessage(errAccId);
throw ex;
Here setMessage() on exception object is important, in order to validate this scenario apply Test Class using the following syntax:
//To validate the scenario in test class
try {
     Controller.Method(”); //calling the controller method with account Id
} catch (AuraHandledException e) {
      System.assert(e.getMessage().contains(‘Account ID not available.’));
}
Showing the error messages in the Component.
To show the error message on the lightning component UI, we would use the following:


Generic reusable message component:
<aura:component access=”global”>
<aura:attribute name=”message” description=”Message content, can be HTML”
                   type=”String” default=”Message from MessageComponent.cmp”/>
<aura:attribute name=”type”
                   description=”Message type, can be error/warning/info/success”
                   type=”String” default=”info”/>
<div class=”{!’slds-box slds-theme–alert-texture slds-theme–‘ + v.type}”>
<lightning:icon iconName=”{! ‘utility:’+ v.type }” size=”medium”
                       alternativeText=”{!v.type}” Class=”iconContainer”/>&nbsp;
<span class=”slds-text-body–regular”>
<aura:unescapedHtml value=”{!v.message}”/>
</span>
</div>
</aura:component>
In the controller/helper:
action.setCallback(this, function(resp) {
if (resp.getState() === “SUCCESS”) {
     component.set(“v.messageType”, ‘success’ );
component.set(“v.message”, ‘Completed Successfully!’ );
}
else if (resp.getState() === “ERROR”) {
     component.set(“v.messageType”, ‘error’ );
var errors = resp.getError();
if (errors) {
if (errors[0] && errors[0].message) {
component.set(“v.message”,errors[0].message );//Fetching Custom Message.
        }
}
else {
component.set(“v.message”, ‘Request Failed!’ );
}
}
});
Using the message component in our component markup:
<c:MessageComponent type=”{!v.messageType}” message=”{!v.message}” />
Eg:
For error message would look like:
<c:MessageComponent type=”error” message=”Account Id Not available.” />
User-added imageSimilar to a warning message, information and success screens could look like:
User-added imageUser-added imageUser-added image
Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra
 
This was selected as the best answer