c# - 如何序列化 Azure 服务总线中的异常?

标签 c# .net serialization azure-webjobs azureservicebus

我正在尝试将 WebJob 执行的异常发送到响应队列:

        var message = new BrokeredMessage(exception);
        outputMessages.Add(message);

我的异常类表示一个逻辑错误:

public class MyException : Exception{
    public MyException(){}
    public MyException(string message) : base(message){}
    public MyException(string message, Exception inner) : base(message, inner){}
    protected MyException(SerializationInfo info, StreamingContext context) : base(info, context){}

    public object MyProp { get; set; }
}

但是,我得到以下异常:

Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.ProcessQueueMessage2Async ---> System.Runtime.Serialization.InvalidDataContractException: Type 'MyException' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

当我用 [DataContract] 标记 MyException 时,我得到了这个:

Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.ProcessQueueMessage2Async ---> System.Runtime.Serialization.InvalidDataContractException: Type 'MyException' cannot be ISerializable and have DataContractAttribute attribute.

可能是因为 System.Exception 实现了 ISerializable。我该如何解决?

最佳答案

您将无法使用 DataContractSerializer 序列化您的异常。即使您成功地使用 DataContract 标记了您的类,内部异常也可以是任何类型,因此不兼容。

所以你有两个选择:

  1. 使用另一个序列化程序序列化您的异常(然后将 Stream 传递给 BrokeredMessage 构造函数)。参见 this question一些选项。

  2. 我认为通过网络发送异常本身并不是很干净。我宁愿创建一个自定义消息,其中包含对消费者很重要的所有信息,然后将此消息发送到服务总线。

关于c# - 如何序列化 Azure 服务总线中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44842424/

相关文章:

在 Activity 之间传递对象时出现 java.io.NotSerializedException

php - 序列化然后反序列化 mysql 结果对象

c# - 如何在 WPF 中使用 SQLite

c# - 使用 C# 像写字板一样嵌入 mspaint

c# - 带重音的字母正则表达式

.net - 如何使特定类型属于类型系列?

c# - 从 WCF 中的抽象类继承而不公开该类

c# - Java - Java 有类似 C# 的结构自动构造函数的东西吗

c# - Type.GetProperties 排除带有运算符 [] 的属性

c# - 通过公共(public)属性访问私有(private)变量