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..!

No comments:

Post a Comment