Overview:
In the actual project development, we often deal with a variety of exceptions, in the code constantly flooded with try{}catch{}finally{} statement blocks, these processes are sometimes indispensable, because there is no way to ensure that the code they write is not abnormal operation, The external environment creates the possibility of an exception, but I often feel that the statement block that captures the exception often makes the original clear business logic pieces, and, of course, the purpose of this article is not to say that exception capture can be avoided completely, but to less WCF allows us to get a little relief from exception handling.
1, first of all, the General Service implementation classes in the handling of exceptions, the following is a general catch a divisor of 0 of the exception.
General Exception capture
public string Div(int x,int y)
{
int result=0;
try
{
result = x / y;
}
catch (DivideByZeroException ex)
{
throw ex;
}
return string.Format("{0}",result);
}
2, then look at the application of the Ierrorhandler interface to deal with the exception after the code.
public string Div(int x,int y)
{
return string.Format("{0}",x/y);
}
Do you feel good? If not, think carefully about exception handling in 1000 methods. This is WCF letting the program throw the exception itself and capture it itself.
3, how to achieve?
3.1, to achieve the above results, we need to customize a class and implement the Ierrorhandler interface, the code is quite simple, as follows:
public class FaultErrorHandler : IErrorHandler
{
#region IErrorHandler 成员
public bool HandleError(Exception error)
{
// TO DO 在这里可以做日志记录等。
Console.WriteLine("Message:{0},StackTrace:{1}",error.Message,error.StackTrace);
return true;
}
public void ProvideFault(Exception error,MessageVersion version,ref Message fault)
{
FaultException fe = new FaultException(error.Message,FaultCode.CreateReceiverFaultCode(error.Source,error.StackTrace));
MessageFault messagefault = fe.CreateMessageFault();
fault = Message.CreateMessage(version,messagefault,"http://www.microsoft.com/");
}
#endregion
}
There are only ten lines of code, equivalent to our previous creation log file code.