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
naveen darshanalanaveen darshanala 

how to handle server-side exceptions in Lightning?

Ravi Dutt SharmaRavi Dutt Sharma
Hi Naveen,

Refer below code:
({
    "echo" : function(cmp) {
        var action = cmp.get("c.serverEcho");
        action.setParams({ firstName : cmp.get("v.firstName") });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                
            }
            else if (state === "INCOMPLETE") {
                // do something
            }
            else if (state === "ERROR") {
                var errors = response.getError();
            }
        });
        $A.enqueueAction(action);
    }
})
When there is a server-side exception, the value of the state variable defined in the callback method will be "ERROR". In the else if block, where we are checking state === "ERROR", you can either console the error, or show a toast message to display the error to end-user.
Ajay K DubediAjay K Dubedi
Hi Naveen,

I have understood your query and I am providing a snippets of code.
Please try it-
 
({
    "echo" : function(cmp) {
        var exp = cmp.get("c.serverEcho");
        exp .setParams({ firstName : cmp.get("v.firstName") });
        exp .setCallback(this, function(response) {
            var state = response.getState();
          
            if (state === "ERROR") {
                var errors = response.getError();
            }
        });
        $A.enqueueAction(exp);
    }
})

Also, refer to this link for more help-

https://developer.salesforce.com/blogs/2017/09/error-handling-best-practices-lightning-apex.html

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com