很多規範中都提到,自訂Exception 要求使用一種統一的建構函式,比如預設實現以下四個建構函式。
[Serializable ]
public class XXXException:ApplicationException
{
public XXXException():base()
{
}
public XXXException(string message):base(message)
{
}
public XXXException(string message,Exception innerException):base(message,innerException)
{
}
protected XXXException ( System.Runtime.Serialization.SerializationInfo info , System.Runtime.Serialization.StreamingContext context ):base(info,context)
{
}
}
這樣做有幾個好處
1. 前三個建構函式可以提供一直的實現方式
2. 最後一個建構函式是對象使用 soap 或者binary formattor 還原序列化的時候比不可少的建構函式。否則你的remoting 物件服務端拋出的異常,無法bubble 到用戶端。
我寫一個簡單的soap formattor 的例子來類比remoting 對象的傳遞
//TODO 1 soap 序列化
XXXException ex=new XXXException("invalid.");
FileStream fs=new FileStream("soap.xml",FileMode.Create );
System.Runtime.Serialization.Formatters.Soap.SoapFormatter sr=new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
sr.Serialize(fs,ex);
fs.Flush();
fs.Close();
//TODO 2 soap 翻序列化
XXXException exp;
FileStream fs1=new FileStream("soap.xml",FileMode.Open);
System.Runtime.Serialization.Formatters.Soap.SoapFormatter dsr=new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
exp=(XXXException)dsr.Deserialize(fs1);
fs1.Close();
MessageBox.Show(exp.Message);
如果沒有xxxexception 的第四個建構函式,可能會有
An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll
Additional information: The constructor to deserialize an object of type ExceptionDemo.XXXException was not found.
當然這個是針對 remoting,web service 走得是 xml serilizer,目前這個版本對 屬性中有申明許可權要求的欄位無法序列化。所以web service 中,你是無法直接講 exception 傳遞給用戶端。
比如一下例子
[WebMethod]
public string HelloWorld(string s,out Exception ex)
{
ex=new FormatException("fasdf");
return "Hello World";
}
你會發現這個例子無法在用戶端調用,呵呵。