2016-03-29 22 views
2

私はSpringMVCコントローラからの例外を処理するために@ControllerAdviceクラスを持っています。 @ExceptionHandlerメソッドで既知の型(RuntimeException)の例外をキャッチして、e.getCause()例外をスローし、この例外を同じ@ControllerAdviceクラスでキャッチしたいとします。@ExceptionHandlerから例外をスローして別のハンドラで捕捉する

サンプルコード:

@ControllerAdvice 
public class ExceptionHandlingAdvice 
{ 
    @ExceptionHandler(RuntimeException.class) 
    private void handleRuntimeException(final RuntimeException e, final HttpServletResponse response) throws Throwable 
    { 
     throw e.getCause(); // Can be of many types 
    } 

    // I want any Exception1 exception thrown by the above handler to be caught in this handler 
    @ExceptionHandler(Exception1.class) 
    private void handleAnException(final Exception1 e, final HttpServletResponse response) throws Throwable 
    { 
     // handle exception 
    } 
} 

これは可能ですか?

答えて

0

あなたはそれのRuntimeExceptionがException1.classのインスタンスであるかどうかを確認し、直接メソッドを呼び出すことができます。

private void handleRuntimeException(final RuntimeException e, final HttpServletResponse response) throws Throwable 
{ 
    if (e instanceof Exception1) handleAnException(e,response); 
    else throw e.getCause(); // Can be of many types 
} 
+0

をのRuntimeExceptionがException1のサブクラスになるだろうことはありませんので、もしチェックが機能しないだろうと。さらに、私はe.getCause()でhandleAnExceptionを明示的に呼び出すことができることを知っています.e.getCause()は多くの異なるタイプの例外を返すことができ、if-else-ifステートメントの醜いブロックで終了します適切なハンドラを手動で呼び出します。次に、その型の正しいハンドラを明示的に呼び出し、各型に対して新しいif節を適用することを忘れないでください。例外を再現し、ControllerAdviceにキャッチしてもらうことができれば、もっときれいになるでしょう。 – agentgonzo

+0

申し訳ありませんが、私は誤解して、Exception1がRuntimeExceptionクラスを拡張していると思っていました。新しいException1(e.getCause())をスローするほど簡単ではありません。 e.getCause()をスローする代わりに? – Mayday

+0

残念ながら、新しい例外をスローすることはハンドラによって捕まえられず、ハンドラのまっすぐなまっすぐ進んで行くだけで、Webコンテナで500のエラーが発生します – agentgonzo

関連する問題