Thursday, December 5, 2019

How To Throw An Exception From Apex (Server Side) To JavaScript(Client Side) Controller in LWC

In lightning if you want to throw something as error from Apex class to client side Js controller ,we can use the salesforce standard class AuraHandledException.

Please look at the below code snippet where I'm trying to call an api to get the weather information,basis on the api response you can throw an exception(received in valid status,received process status but didn't got the expected response etc..) wherever you want throw an exception to the client side controller.

If your using try and catch in your code and if you raise an exception in try it will automatically goes to catch block and from there it will return to client side controller.


global class WeatherReportCntrl
{

@AuraEnabled(cacheable=true)
public static string fetchWeatherReport()
{
   Http http = new Http();
   HttpResponse res = new HttpResponse();
   HttpRequest req = new HttpRequest();
   req.setEndpoint('endpoint');
   req.setMethod('GET');
   try
    {
 res = http.send(req);                      
 string responseValue =res.getBody();
 if(res.getStatus()=='OK' && res.getStatusCode()==200 && String.isNotBlank(responseValue)
 {
    //while processing some error came then
    System.debug('responseValue--->'+responseValue);
    if(someerror)
     throw new AuraHandledException('Error while Processing data');  

   return 'data processed successfully';
 }
 else
       {
 // Received some invalid status code
  throw new AuraHandledException('Received some invalid status');
 
 }
    }
   Catch(Exception e)
   {
       AuraHandledException ex = new AuraHandledException(String.valueOf(e));
       ex.setMessage('Exception caught in catch block');
       throw ex;
   }
 } 
}


Hope this helps you..Enjoy..!

6 comments:

  1. Replies
    1. Handling exceptions between Apex server-side code and JavaScript client-side controllers is an important aspect of building reliable Salesforce Lightning Web Components (LWC). Using AuraHandledException allows developers to communicate meaningful error messages from Apex to the client side. The combination of try-catch blocks and proper HTTP response validation also helps manage API failures and unexpected responses more effectively.

      Understanding JavaScript exception handling, asynchronous operations and communication between application components is valuable when developing interactive applications. Practical learning through Javascript Online Course helps developers strengthen their programming fundamentals and understand how client-side code handles server responses and errors.

      Delete
    2. For developers working with APIs and server-side integrations, understanding how JavaScript processes exceptions returned by backend services is equally important. Building these skills through Javascript Online Training can help improve error handling, debugging and application reliability.

      Delete