Exception handling is critical to all applications for troubleshooting the unexpected problems in applications. The Windows Communication Framework (WCF) provides several options for handling exceptions in WCF services. This article discusses these approaches and describes the advantages and disadvantages of each. The following options are provided to handle exceptions in WCF:
- Using returnUnknownExceptionsAsFaults: Debugging Mode
- Using FaultException: Best Option.
- Using IErrorHandler: Only when the exception can't be handled by Fault
Exception handling in WCF
Exceptions inside a WCF Service
Before describing the details of exception handling in WCF, let's explore what happens if we do not handle an exception inside the service. Consider a service with the CreateUser method as shown in the following:
- public void CreateUser(User user)
- {
- if(user.isValid())
- {
-
- }
- else
- {
- throw new ApplicationException(“User Inavalid.”);
- }
- }
Example
- public class DBManagerService: IDBManagerService
-
- void Save(Employee emp)
- {
- try
- {
-
- }
- catch (Exception ex
- {
- throw new Exception(“Error occurred
- while saving data…”);
- }
- }
- }