我正在尝试将 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
标记了您的类,内部异常也可以是任何类型,因此不兼容。
所以你有两个选择:
使用另一个序列化程序序列化您的异常(然后将
Stream
传递给BrokeredMessage
构造函数)。参见 this question一些选项。我认为通过网络发送异常本身并不是很干净。我宁愿创建一个自定义消息,其中包含对消费者很重要的所有信息,然后将此消息发送到服务总线。
关于c# - 如何序列化 Azure 服务总线中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44842424/