Saturday, June 9, 2012

Receiving Exception in Silverlight from WCF (Exception Handling in WCF)

Any error comes in the WCF service it returns Remote Server returned an Error. To avoid this.

There is a better way to handle exception from WCF service and send those exception to Silverlight client if you really want to receive exceptions at client end.

Follow the below step

[DataContract]
public class CustomException
{
   
      public CustomException(Exception ex)
     {
          this.Message=ex.Message;
         this.StackTrace=ex.StackTrace;
      }
      public string Message{get;set;}
   
     public string StackTrace{get;set;}
 
 
}


[OperationContract]
public int Divide(int a, int b,out CustomException ServiceError)
{
        try
       {
            ServiceError=null;/*out parameter must be assigned inside the method*/
            return a/b;
       }
      catch(Exception ex)
     {
          ServiceError=new CustomException(ex);
          return -1;
     }
}

while in the completed method you have to check something like this

if(e.ServiceError==null)/*this means there is no error in the service*/
 {
           
 }
else
{
///////////////this means service has got error
/*Notify the user if you want to inform of perform whatever you want in case of error*/
MessageBox.Show(e.ServieError.Message);
}

Let me know your comments and Suggestion on this.

Cheers!
Vinod


No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog