IOExceptionやClassNotFoundExceptionなどの例外をチェックするために、Spring Webアプリケーションを開発すると、コンパイラはしばしば、プログラマーにtry-catch使用して明示的なキャプチャを使用するように促します。 ClassCastExceptionやNullPointerExceptionなどの非チェックの例外の場合、コンパイラはあなたに促されません。これは多くの場合、プログラマーのコードライティング能力を反映する側面です。
Spring Web、特にSpring-Bootアプリケーションでは、リクエストが正常に呼び出されると、通常、下の図に示すように、 json形式のオブジェクトを返します。
しかし、リクエストがRuntimeExceptionをスローした場合はどうなりますか?処理を行わない場合、次のページが再度電話をかけたときに表示されます。
つまり、呼び出しでエラーが発生した場合、スプリングブートはリクエストをデフォルトで/errorパスにマッピングします。対応するパス要求プロセッサがない場合、上記のWhitelabelエラーページに戻ります。
1.エラー処理ページをカスタマイズします
もちろん、ランタイムの例外を処理しないことは不可能です!通常の練習は、統一されたエラーページをカスタマイズしてから返すことです。上記のアイデアによれば、 /errorの要求パスでコントローラーを実装します。コントローラーはリソースパスアドレスを返し、 /errorの要求マップパスを持つコントローラーを定義し、 ErrorControllerインターフェイスを実装します。コードは次のとおりです。
MyErrorPageController
パッケージcom.example.demo.controller.handler.errorpage; Import org.springframework.boot.web.servlet.error.errorcontroller; Import org.springframework.stereotype.controller; Import org.springframework.web.wab.notation.Requestmapping; myerrorpagecontroller。 * *説明:カスタムエラーページ * * @author:huangjiawei * @since:2018年6月13日 * @version:$ revision $ $ $ $ $ $ $ $ $ $ changedby $ * */ @controllpublic class myerrorpagecontrollerは、エラーコントローラー{ @requestmapping( "/error")public string condreerror( "){/error") //このリソースはリソース/staticディレクトリにあります} @override public string getErrorPath(){return null; }}次に、 reosurces/static Directoryにerror.htmlファイルを作成します。
<!doctype html> <html> <head> <meta charset = "utf-8"> <title>挿入</title> </head> <body> <h1>これはエラーページです!リソース/静的ディレクトリに保存されています。デフォルトの呼び出しは、スプリングブートエラー</h1> </body> </html>です
http://localhost:7000/demo/getUserInfoWithNoHandler.json次のようにリクエストしてください。
@ControllerAdvice 、 @ResponseBody 、および@ExceptionHandlerを使用して、例外を均一に処理する
春には、上記の3つの注釈を統一された例外処理に使用できます。デフォルトでは、システムに表示される特定のタイプの例外のために、統一されたプロセッサハンドラーを定義できます。たとえば、システムがNullPointerExceptionをスローする場合、 NullPointerException専用のプロセッサを定義できます。コードは次のとおりです。
getUserInfoWithNullPointerExceptionインターフェイス
/** * nullポインターエラーの取り扱い * @return * @throws nullpointerexception */ @requestmapping(value = "getuserinfowithnullpointerexception.json"、method = requestmethod.get)Public Student getuserinfowithNullpointerexception()Shrows NullPoInterexception()
NullPointerExceptionHandler.java
パッケージcom.example.demo.controller.handler; import org.springframework.web.bind.annotation.controlleradvice; Import org.springframework.web.bind.annotation.exceptionHandler; Import org.springframework.web.bind.annotation.responperbody; import com.example.demo.pojo.errorreturn;/** * *クラスnullpointerexceptionhandler。 * *説明:nullポインターを処理 * * @author:huangjiawei * @since:2018年6月13日 * @version:$ revision $ $ $ $ $ $ $ $ $ $ $ $ changedby $ * */ @ @controlleradvicepublic class e.printstacktrace(); errorReturn error = new errorReturn(); error.setreturnCode( "-1"); error.setDesc( "Null Pointer例外が発生しました!");エラーを返します。 }}
ブラウザの実行: http://localhost:7000/demo/getUserInfoWithNullPointerException.json
同様に、他のランタイム例外のために統一プロセッサを提供する必要がある場合は、上記のように各例外タイプのプロセッサを定義することもできます。たとえば、 ArithmeticException用のプロセッサを定義する場合は、クラスまたはメソッドを作成してから、 ArithmeticException.class @ExceptionHanlerアノテーションに追加する必要があります。
ただし、このように、各例外タイプの例外処理クラスまたはメソッドを定義していることがわかりました。実行時には多くの例外タイプがあるため、各タイプのプロセッサクラスまたはメソッドを指定することは不可能です。この場合、春はそれを解決することもできます。 ArithmeticExceptionなどの特定のタイプの例外のプロセッサを定義しない場合、 ExceptionまたはThrowableプロセッサを定義して均一に処理できます。
これを行うことの利点は、プロセッサクラスの数を減らし、例外処理を親クラスに転送することです。これは、継承の大きな利点でもあります。ただし、特定のタイプの例外とExceptionのプロセッサを同時に定義する場合、注意してください。ここには必ずしも優先関係があるわけではありません。つまり、親例外プロセッサのみが実行されるとは限りません。 Bプロセッサだけでなく、Aプロセッサではなく、Bプロセッサだけでなく、プロセッサAのみを実行できます。たとえば、 NullPointerExceptionHandler例外はExceptionに渡されます(ただし、 ArithmeticException Exceptionに渡されません)
次に、上のNullPointerExceptionHandlerと以下のExceptionThrowableHandlerの両方を定義するとします。次に、 NullPointerExceptionが発生すると、デフォルトでExceptionThrowableHandlerメソッドが実行されます。
ExceptionThrowableHandler.java
パッケージcom.example.demo.controller.handler; import org.springframework.web.bind.annotation.controlleradvice; Import org.springframework.web.bind.annotation.exceptionHandler; Import org.springframework.web.bind.annotation.responperbody; import com.example.demo.pojo.errorreturn;/** * *クラスの例外を導くことができます。 * *説明:いくつかの例外は高レベルの例外に渡されます(ただし、arithmeticexceptionは例外に送信されません) errorReturn dealthrowable(){errorReturn error = new errorreturn(); error.setDesc( "ハンドルスロー可能!"); error.setreturnCode( "-1");エラーを返します。 } @exceptionHandler(exception.class)@responsebody public errorreturn dealcommonexception(){errorreturn error = new errorreturn(); error.setreturnCode( "-1"); error.setDesc( "パブリック例外処理!");エラーを返します。 }}ブラウザの実行: http://localhost:7000/demo/getUserInfoWithNullPointerException.json
Exceptionのみを実行するが、nullポインターを実行しないプロセッサ、つまり例外処理が上向きに送信されることがわかります。 ArithmeticExceptionがスローされる状況を見てみましょう。
getUserInfoWithArithmeticException.json
/** * nullポインターエラーの処理のテスト * @return * @throws nullpointerexception */ @requestmapping(value = "getUserinfowitharithexcection.json"、method = requestmethod.get)Public Student getuserinfowitharitheTicexcection()Throws arithmeticexception {leth aritheticexcection() ArithmeticExceptionHandler.java
パッケージcom.example.demo.controller.handler; import org.springframework.web.bind.annotation.controlleradvice; Import org.springframework.web.bind.annotation.exceptionHandler; Import org.springframework.web.bind.annotation.responperbody; import com.example.demo.pojo.errorreturn; @controlleradvicepublic class arithmeticexceptionhandler { / *** handle arithmeticexceptionecception exception* / @responsebody @exceptionhandler(arithmeticexception.class)class)errerturn = err errorturn errorobject.setreturnCode( "-1"); errorobject.setDesc( "例外は算術処理で発生しました!"); return errorobject; }}ブラウザの実行: http://localhost:7000/demo/getUserInfoWithArithmeticException.json
その結果、例外処理は上位レベルのExceptionHandlerに送信されなかったことがわかりました。
概要:特定のタイプとExceptionなどの親タイプの両方のプロセッサを定義する場合は、特に注意してください。すべての例外が上位レベルで処理されるわけではありません。プロセッサクラスの数のみを減らし、特定の種類のプロセッサの各タイプのクラスまたはメソッドを追加したくない場合は、エディターがキーワードinstanceofを使用して例外タイプを判断することをお勧めします。
次のコードと同様に、パブリック例外ハンドラーのみを確立し、例外Exceptionを処理し、 instanceofを使用して判断を下します。
@exceptionHandler(Exception.Class)@ResponseBodyPublic ErrorReturn DealCommonexception(Exception E){ErrorReturn Error = new ErrorReturn(); //ここで、InstanceOfを使用して例外タイプを決定できます。IF(e InstanceOf arithmeticexception){error.setreturnCode( "-1"); error.setDesc( "arithmeticexception処理!");エラーを返します。 } system.err.println( "例外"); error.setreturnCode( "-1"); error.setDesc( "パブリック例外処理!");エラーを返す;}ブラウザは、次のように、 ArithmeticExceptionをスローするインターフェイスを実行します。
この記事のコードアドレス:https://github.com/smallercoder/spring_exceptionhandler
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。