2017-06-30 40 views
1

我試圖發送一個異常作爲WebJob執行,以響應隊列的結果:如何序列化Azure Service Bus中的異常?

 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.

當我標誌着MyException[DataContract]我得到這個:

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。我該如何解決這個問題?

+0

「向響應隊列發送異常」 - 接收者真的需要整個Exception *對象嗎?或者用'.ToString()',或者一個狀態碼或者一些自定義的消息包更好? – AakashM

+0

恐怕我不能使用字符串或枚舉,因爲我需要傳遞其他信息(在我的示例中爲'MyProp'),以正確格式化UI上的錯誤消息。 – UserControl

回答

4

您將無法將您的例外序列化爲DataContractSerializer。即使您成功標記了DataContract類,內部異常也可以是任何類型,因此不兼容。

所以,你有兩個選擇:

  1. 序列化與另一串的異常(然後傳遞到Stream構造BrokeredMessage)。有些選項參見this question

  2. 我會爭辯說,通過電線發送異常本身並不是很乾淨。我寧願創建一個自定義消息,其中包含對消費者很重要的所有信息,然後將此消息發送到服務總線。