Finally, the order of capturing the exception is given in the paper. This exception capture is for introduction only, partly for applicability, so the code and writing are relatively simple, and some tips on server-side exception handling are also described.
1, first, we create a simple calculator server and client, as follows:
Click Expand Code
//服务器
[ServiceContract]
public interface ICalc
{
[OperationContract]
[FaultContract(typeof(GreentingError))]
string Div(int x, int y);
}
public class Calc : ServiceBase, ICalc
{
public string Div(int x, int y)
{string result = string.Empty;
try
{result = string.Format("result: {0}", x / y); } catch (DivideByZeroException ex)
{throw ex; }return result; }}
//客户端
[ServiceContract]
public interface ICalc
{
[OperationContract]
[FaultContract(typeof(GreentingError))]
string Div(int x, int y);
}
public class CalcClient : ClientBase<ICalc>, ICalc
{ public string Div(int x, int y) {return base.Channel.Div(x, y); }}
Well, I admit the code is fairly simple, but I like the simplicity of things.
2, the simple thing is good, the call is much simpler; let's call it.
try
{
CalcClientcalcclient = new CalcClient();
string result =calcclient.Div(10, 0);
Console.WriteLine(result);
Console.ReadKey();
}
catch (TimeoutExceptionex) {throw ex; }
catch (FaultException<GreentingError> ex) {throw ex; }
catch (FaultExceptionex) {throw ex;
catch (System.ServiceModel.CommunicationException ex) {throw ex; }
catch (Exceptionex) {throw ex; }
3. When we call the div (int x,int y) method of the service and pass a value of 0 to the logarithmic y, the server side will throw a DivideByZeroException exception, which is expected. When
This exception was caught in the faultexception section of the client.
4, no problem, we will manually throw the faultexception exception in the server code.
catch (DivideByZeroException ex)
{FaultException exception = new FaultException(ex.Message); throw exception;}
At this time found, or faultexception caught this anomaly, why?