在 C# 中,如何序列化 System.Exception?(.Net CF 2.0) [英] In C#, how can I serialize System.Exception? (.Net CF 2.0)
问题描述
我想将异常写入 MS 消息队列.当我尝试它时,我得到了一个例外.所以我尝试使用 XmlSerializer 来简化它,但它仍然引发异常,但它给了我更多信息:
I want to write an Exception to an MS Message Queue. When I attempt it I get an exception. So I tried simplifying it by using the XmlSerializer which still raises an exception, but it gave me a bit more info:
{"有一个错误反映类型'System.Exception'."}
{"There was an error reflecting type 'System.Exception'."}
带有内部异常:
{"无法序列化成员System.Exception.Data 类型System.Collections.IDictionary,因为它实现了 IDictionary."}
{"Cannot serialize member System.Exception.Data of type System.Collections.IDictionary, because it implements IDictionary."}
示例代码:
Exception e = new Exception("Hello, world!");
MemoryStream stream = new MemoryStream();
XmlSerializer x = new XmlSerializer(e.GetType()); // Exception raised on this line
x.Serialize(stream, e);
stream.Close();
我试图保持这个尽可能简单,但我可能做得过头了.我想要整个位、堆栈跟踪、消息、自定义异常类型和自定义异常属性.我什至可能想再次抛出异常.
I tried to keep this a simple as possible, but I may have overdone it. I want the whole bit, stack trace, message, custom exception type, and custom exception properties. I may even want to throw the exception again.
推荐答案
我认为你基本上有两个选择:
I think you basically have two options:
- 自己手动序列化(可能不想这样做).由于您在内部异常中获得的确切消息,XML 序列化肯定无法工作.
- 创建您自己的自定义(可序列化)异常类,将抛出的异常中的数据注入您的自定义异常类中并对其进行序列化.
这篇关于在 C# 中,如何序列化 System.Exception?(.Net CF 2.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!