.net - 将异常对象传递给 Web 服务

标签 .net web-services exception

继一个问题 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/

相关文章:

java - 在服务器应用程序中对异常进行建模并处理 http 代码

java - If-Else 语句 vs Exception-Catcher?

远程连接到 SQL Server 2005 实例时出现 C# 异常

c# - 注册动态类型的简单注入(inject)器

silverlight - 来自 WP7 应用程序的安全/经过身份验证的交互

asp.net - 调用 webservice 时服务器响应状态为 500(内部服务器错误)

c# - 为什么要使用只有一个参数的 string.Format 呢?

.net - 带有.Net的Oracle高级队列

java - Jax ws- xs :date format validation

c++ - 捕获命名空间限定的异常