1は、カスタム例外を追加し、RuntimeExceptionが、なぜそれはRuntimeException継承しますか?私たちのトランザクションのロールバックが例外RuntimeExceptionの下で発生したため。
1 パブリック クラス BusinessExceptionが延びているのRuntimeException { 2 3 公共BusinessException(文字コード、文字列MSG){ 4 本 .CODE = コード; 5 本 .MSG = MSG。 6 } 7 8 プライベート文字列コードと 9 プライベート文字列のMSG。 10 11 公共の文字列にgetCode(){ 12 リターンコードと 13 } 14 公共 ボイドSETCODE(文字コード){ 15 本.CODE = コード。 16 } 17 18 公衆ストリングGETMSG(){ 19 リターンMSG。 20 } 21 22 公共 ボイドsetMsg(文字列MSG){ 23 この .MSG = MSG。 24 } 25 26 }
2、@RestControllerAdviceを達成するために注釈を使用し、キャッチグローバル例外を追加
1 パブリック クラスCustomExtHandler { 2 3 プライベート 静的 最終ロガーLOG = LoggerFactory.getLogger(CustomExtHandler。クラス)。 4 5 6 // 捕获全局异常、处理所有不可知的异常 7 @ExceptionHandler(値=例外。クラス) 8 オブジェクトhandleException(例外e、HttpServletRequestのリクエスト){ 9 LOG.error( "URL {}、MSG {}" 、request.getRequestURL()、e.getMessage())。 10 地図<文字列、オブジェクト>マップ= 新しい HashMapの<> (); 11 map.put( "コード"、100); 12は map.put( "MSG" ;、e.getMessage()) 13である map.put( "URL" 、request.getRequestURL()); 14 リターンマップ; 15 } 16 17 / ** 18である *説明:処理カスタム例外クラス 19 * @return 20は、 * 21である / * 22である @ExceptionHandler(値= BusinessException。クラス) 23である {handleMyException(BusinessException E、HttpServletRequestの要求の)オブジェクト 24 // FのJSONデータを返す 25 地図の<string、オブジェクト>マップ= 新新HashMapの<> (); 26 map.put( "コード" 、e.getCode())。 27 map.put( "MSG" 、e.getMsg())。 28 map.put( "URL" 、request.getRequestURL()); 29 リターンマップ。 30 }
使用して3、
1 スロー 新しい新 BusinessException( "200"、 "間違ったああ!");