2012-03-24 163 views
9

我在四處搜索Netty的異常處理模式,但是我找不到太多。Netty異常處理 - Handler拋出異常,那麼是什麼?

某種異常處理指南會很棒。我有拋出的異常被髮送到exceptionCaught,但我不知道下一步該怎麼做。

有人可以提供一個通用的解釋如何在Netty中處理異常。處理從ChannelHandler拋出的異常的預期模式是什麼?

謝謝, 馬特

回答

2

這真的取決於你的實現和異常的類型。有時你可能會恢復,有時候它可能是最好的關閉頻道。

所以我認爲它不可能告訴你如何處理它..

2

同意諾曼。

通常,我嘗試捕獲並處理所有應用程序異常並返回包含錯誤的正確消息。

例如,在HTTP服務器中,如果找不到文件,我會返回404。

我還在我的處理程序中添加了以下函數,用於我沒有捕捉到的任何異常 - 理論上應該只是網絡類型錯誤。我傾向於對這些例外採取黑白方法,並假設我無法恢復。因此,我關閉了頻道。這將由客戶再試一次。

@Override 
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { 
    try { 
     _logger.error(e.getCause(), "ERROR: Unhandled exception: " + e.getCause().getMessage() 
       + ". Closing channel " + ctx.getChannel().getId()); 
     e.getChannel().close(); 
    } catch (Exception ex) { 
     _logger.debug(ex, "ERROR trying to close socket because we got an unhandled exception"); 
    } 
} 

希望這會有所幫助。

3

正如Norman和Veebs都提到的那樣,在不瞭解您的具體要求的情況下,提供準確的答案有點棘手...... 我認爲以下提供了一種處理服務器錯誤的通用方法,您並不期待。它向客戶端返回HTTP 500'內部服務器錯誤',然後關閉該通道。顯然,我假設你的客戶正在請求並通過HTTP接收他們可能不是的,在這種情況下,Veebs的解決方案更好。

import org.jboss.netty.channel.ChannelFutureListener; 
import org.jboss.netty.channel.ChannelHandlerContext; 
import org.jboss.netty.channel.ExceptionEvent; 
import org.jboss.netty.channel.SimpleChannelHandler; 
import org.jboss.netty.handler.codec.http.DefaultHttpResponse; 
import org.jboss.netty.handler.codec.http.HttpResponse; 
import org.jboss.netty.handler.codec.http.HttpResponseStatus; 
import org.jboss.netty.handler.codec.http.HttpVersion; 

public class ServerErrorHandler extends SimpleChannelHandler { 
    @Override 
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) 
     throws Exception { 
     HttpResponse err = new DefaultHttpResponse(HttpVersion.HTTP_1_1, 
              HttpResponseStatus.INTERNAL_SERVER_ERROR); 
     e.getChannel().write(err).addListener(ChannelFutureListener.CLOSE); 
    } 
} 

注意,如果您使用此解決方案,那麼您還需要將HttpResponseDecoder添加到管道中。

顯然,如果你有特定的例外,你想趕上和處理,那麼你會在這裏寫一些額外的邏輯來做到這一點。

HTH!

相關問題