2013-08-26 109 views
2

我明白讓NServiceBus處理錯誤並讓它重試或使用第二級重試,這對於應用程序中的一些未知錯誤是有效的。NServiceBus錯誤處理

例如,假設它是transactionId == null,那麼我不只是想拋出異常,讓NService總線處理它,因爲我知道這永遠不會通過任何額外的嘗試。 對於已知的異常情況,最好的做法是什麼?

我正在使用傳說中哪些不同的端點(A,B,C,D)。你如何處理在這個端點上面的錯誤情況,因爲我不想讓我的傳奇處於懸掛狀態。

+1

我在下面的答案的同一行沒有這個有用的http://andreasohlund.net/2012/09/26/disabling-second-level-retries-for-specific-exceptions/ – Miral

回答

0

如果你有一個異常(或者一類異常),你知道沒有重試次數會有幫助,那麼你是正確的,最好是快速失敗。

讓我們假設你有一個這樣的處理程序..

public void Handle(BadMath message) 
{ 
    var zero = 0; 
    var crash = 5/zero; 
    var msg = "I will never be reached..."; 

    this.SendReply(msg); 
} 

而且要陷阱&快速失敗的DIV/0 ...

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using NServiceBus; 
using NServiceBus.Features; 
using NServiceBus.SecondLevelRetries.Helpers; 

namespace My.Namespace.Messaging.Handlers 
{ 
    public class ChangeRetryPolicy : INeedInitialization 
    { 
     public void Init() 
     { 
      Configure.Features.Disable<SecondLevelRetries>(); 

      Configure.Features.SecondLevelRetries(s => s.CustomRetryPolicy((tm) => 
      { 
       // retry max 3 times 
       if (TransportMessageHelpers.GetNumberOfRetries(tm) >= 3) 
       { 
        // To send back a value less than zero tells the SecondLevelRetry 
        // satellite not to retry this message anymore. 
        return TimeSpan.MinValue; 
       } 

       if (tm.Headers["NServiceBus.ExceptionInfo.ExceptionType"] == typeof(System.DivideByZeroException).FullName) 
       { 
        return TimeSpan.MinValue; 
       } 
       return TimeSpan.FromSeconds(5); 
      })); 

      Configure.Features 
     } 
    } 

} 

如果您嘗試運行處理程序通過一個單元測試,測試當然會炸燬並拋出一個錯誤。 如果你在 「crash = 5/zero」, 處理程序中放置了一個斷點,然後重新運行你的項目,你會發現當NServiceBus嘗試重新傳送消息時,二級重試不會發生,並且你的未傳送直接進入錯誤隊列。