代碼規範 自訂 Exception

來源:互聯網
上載者:User

很多規範中都提到,自訂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";

  }

你會發現這個例子無法在用戶端調用,呵呵。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.