继一个问题 here让我思考....
当应用程序遇到未处理的异常时,是否有可能将此异常对象序列化并发送到具有 db 后端的 Web 服务。然后,使用实用程序或什至在 Visual Studio 中,异常对象可以从数据库加载并检查?
这可能吗?我想第一个问题是您是否可以序列化异常对象。
最佳答案
您可以序列化异常对象。在 Web 服务调用中抛出异常的情况下,这实际上是将异常对象从服务器传输到客户端所需要的。这就是为什么System.Exception
有一个 constructor overload that creates an exception object from serialized data .
序列化/反序列化异常对象的代码示例:
private static void SerializeException(Exception ex, Stream stream)
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, ex);
}
private static Exception DeserializeException(Stream stream)
{
BinaryFormatter formatter = new BinaryFormatter();
return (Exception)formatter.Deserialize(stream);
}
// demo code
using (Stream memoryStream = new MemoryStream())
{
try
{
throw new NullReferenceException();
}
catch (Exception ex)
{
// serialize exception object to stream
SerializeException(ex, memoryStream);
memoryStream.Position = 0;
}
// create exception object from stream, and print details to the console
Console.WriteLine(DeserializeException(memoryStream).ToString());
}
话虽如此,我可能会满足于在某处记录异常类型、消息和堆栈跟踪,以便我可以检查信息。
关于.net - 将异常对象传递给 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1109802/