我寫了一個自定義的異常對象。這是因爲我想在發生錯誤時跟蹤附加信息。我的CLR對象的定義如下:錯誤序列化CLR對象以用於WCF服務
public class MyException : Exception
{
public override string StackTrace
{
get { return base.StackTrace; }
}
private readonly string stackTrace;
public override string Message
{
get { return base.Message; }
}
private readonly string message;
public string Element
{
get { return element; }
}
private readonly string element;
public string ErrorType
{
get { return errorType; }
}
private readonly string errorType;
public string Misc
{
get { return misc; }
}
private readonly string misc;
#endregion Properties
#region Constructors
public MyException()
{}
public MyException(string message) : base(message)
{ }
public MyException(string message, Exception inner) : base(message, inner)
{ }
public MyException(string message, string stackTrace) : base()
{
this.message = message;
this.stackTrace = stackTrace;
}
public MyException(string message, string stackTrace, string element, string errorType, string misc) : base()
{
this.message = message;
this.stackTrace = stackTrace;
this.element = element;
this.errorType = errorType;
this.misc = misc;
}
protected MyException(SerializationInfo info, StreamingContext context) : base(info, context)
{
element = info.GetString("element");
errorType = info.GetString("errorType");
misc = info.GetString("misc");
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("element", element);
info.AddValue("errorType", errorType);
info.AddValue("misc", misc);
}
}
我已經在WP7應用程序中創建這個定製xception的副本。唯一的區別是,我沒有定義GetObjectData方法或定義了SerializationInfo的構造函數。如果我按原樣運行應用程序,則會收到一條錯誤消息:
類型'My.MyException'無法序列化。考慮使用DataContractAttribute屬性標記它,並使用DataMemberAttribute屬性標記要序列化的所有成員。如果類型是一個集合,請考慮使用CollectionDataContractAttribute來標記它。
如果我添加了DataContract /的DataMember屬性的類和服務器端的相應的成員,我收到一個錯誤,指出: 類型不能ISerializable的和具有DataContractAttribute屬性。
如何序列化MyException,以便我可以將它的實例傳遞給我的WCF服務。請注意,我想使用我的服務從Android應用程序。正因爲如此,我不想做任何過於以微軟爲中心的事情。這是我對DataContract/DataMember的擔心。
非常感謝您的幫助!
我試圖序列化異常的原因是因爲我傳遞一個異常到WCF服務。原因是因爲我正在捕獲移動應用程序中發生的異常,並且想將它們登錄到我的服務器上,所以我知道在哪裏尋找錯誤。據說,我該怎麼做? – user208662 2011-02-05 17:10:02
爲什麼不改用「ex.ToString()」? – 2011-02-05 17:12:47