Exception Handling in WCF

Source: Internet
Author: User
Tags exception handling

Exception messages are related to specific technologies. NET exception, WCF does not support the traditional method of exception handling. If the exception is handled in a traditional manner in a WCF service, the client cannot receive an exception that is thrown by the service because the exception message cannot be serialized, such as a service design:

[ServiceContract(SessionMode = SessionMode.Allowed)]
public interface IDocumentsExplorerService
{
  [OperationContract]
  DocumentList FetchDocuments(string homeDir);
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class DocumentsExplorerService : IDocumentsExplorerService,IDisposable
{
public DocumentList FetchDocuments(string homeDir)
{
  //Some Codes

  if (Directory.Exists(homeDir))
  {
    //Fetch documents according to homedir
  }
  else
  {
    throw new DirectoryNotFoundException(
string.Format("Directory {0} is not found.",homeDir));
  }
}
public void Dispose()
{
  Console.WriteLine("The service had been disposed.");
}
}

The client cannot get the exception when it invokes a service operation such as the following:

catch (DirectoryNotFoundException ex)
{
  //handle the exception;
}

To remedy this flaw, WCF treats unrecognized exceptions as FaultException exception objects, so the client can catch FaultException or exception exceptions:

catch (FaultException ex)
{
  //handle the exception;
}
catch (Exception ex)
{
  //handle the exception;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.