カスタム例外springMVC&springCloud

、springMVCカスタム例外処理

異常なスローコントローラー集中処理:

珍しい0/1のコントローラ

1  @Controller
 2 @RequestMapping( "/テスト" 3。 パブリック クラスTestControllerは{
 4。 
5。 
6。     / ** 
7。      *戻り値接頭辞:接頭ビューリゾルバプレフィックスとサフィックスがスプライスされることはありません
 8。      *リダイレクト:リダイレクト
 9       *フォワード:フォワード要求
 10       * @return 
11。      * / 
12である      ( "/たTestStringを" @RequestMapping 13は     公衆ストリングたTestString(){
 14          のSystem.out.println(1/0 );
 15          リターン "リダイレクト:testModelAndViewは" ;
 16      }
17  
18  
19  
20  
21  
22  
23 }

 

Exceptionクラス(分析異常解決)

バックユーザーフレンドリーにメッセージを指定します

ジャンプerror.jspを指定します

プログラマは、コンソールに何も異常を調べることができます


        ex.printStackTrace();
@Component
 パブリック クラス MyHandlerException 実装HandlerExceptionResolver {
     / ** 
     *異常解析
     * @paramのリクエスト要求オブジェクト
     *の@paramのレスポンスレスポンス
     * @paramのハンドラプロセッサ
     * @param EXは、撮影した例外オブジェクト
     * @returnの  モデルとビューオブジェクト
      * / 
    @オーバーライド
    公共のModelAndView resolveException(HttpServletRequestのリクエスト、レスポンスHttpServletResponseの、ハンドラオブジェクト、例外EX){ 

        ex.printStackTrace(); 
        のModelAndViewのModelAndView = 新しい新ModelAndView(); 
        modelAndView.addObject( "メッセージ"、 "システムエラーは、管理者に連絡してください!!" ); 
        modelAndView.setViewName( "エラー" ); 

        を返すのModelAndViewを; 
    } 
}

 

春-mvc.xml

1の<?xml version = "1.0"エンコード= "UTF-8"?>
 2 <豆のxmlns = "http://www.springframework.org/schema/beans"
 3つ         のxmlns:XSI = "のhttp:// WWW。 「w3.org/2001/XMLSchema-instance
 4つの         http://www.springframework.org/schema/context:コンテキスト=のxmlns ""
 5つ         のxmlns:MVC = "http://www.springframework.org/schema/mvc"
 6         XSI:のschemaLocation = "http://www.springframework.org/schema/beans
 7         のhttp:// www.springframework.org/schema/beans/spring-beans.xsd 
8         のhttp:// www.springframework.org/スキーマ/コンテキスト
9         のhttp://www.springframework.org/schema/context/spring-context.xsd 
10         のhttp:// www.springframework.org/schema/mvc 
11         のhttp:// www.springframework.org/schema/mvc/spring-mvc.xsd」 > 
12      <! -开启注解扫描- >
 13      <文脈:コンポーネントスキャン塩基パッケージ = "com.example"> </コンテキスト:コンポーネント・スキャン>
 14  
15      <! -视图解析器- >
 16      <ビーンクラス = "org.springframework.web.servlet.view.InternalResourceViewResolver">
 17          <プロパティ名= "接頭辞"値= "/ WEB-INF /"> </プロパティ>
 18          <
プロパティ名= "サフィックス" 値= "JSP"> </ property>の19      </ビーン>
 20である      < -駆動MVC注釈:!自動ローディング処理マッピング処理アダプタ- >
 21れる      <MVC:注釈ドリブン> </ MVC:注釈ドリブン>
 22である </豆>

 

WEB-INFでerror.jsp

<%@ページisELIgnored = "false"の場合のcontentType = "text / htmlの;のcharset = UTF-8"言語= "javaの" %> 
<HTML> 
<HEAD> 
    <TITLE>タイトル</ TITLE> 
</ HEAD> 
<BODY> 
    $ {メッセージ}
 </ BODY> 
</ HTML>

 

 

 

第二に、カスタム例外処理springcloud

背景問題

コードの冗長性、のtry-catchあまりにも多くの不適切。

このようなユーザ操作など不正なユーザー体験が、「」「操作が失敗した」を返し、それが具体的にどのような異常が不明です

解きます

すべてのグローバル例外ハンドラは2例を捕捉した後、例外(@ControllerAdvice)を捕獲しました:

 

1.カスタム例外(CustomerException)は、侵襲的なコードがあるので、例外を継承してはならないが、また、スローするように継続するので、相続のRuntimeException

2.予測できない異常なシステムレベル(ヌルポインタ、接続タイムアウト...)、キー、値フレンドリ情報として異常なクラス。

マップ内の例外クラスのキーは、戻り値のプロンプトが存在する場合、クエリは、マップ内の例外クラス固有の情報を返さなかった場合。

(A)カスタム例外の例

「スロー4CustomerExceptionクラス2で - 」の1-実行順序は、この例外ハンドラを処理するために、特に3で、3をキャッチされ、ユーザ固有の情報に戻った異常情報を取得します。

1つの異常

ExceptionCast.cast(Code.EXIT)。

2ExceptionCastクラス(クラスの例外がスローされます)と
3ExceptionCatch(クロール型)
1つの パブリック クラスExceptionCast {
 2  公共 静的 ボイドキャスト(のResultCodeのresultCode){
 3       新しいCustomerException(resultCodeが)。
4  
5  }
 6  
7  
8 }
 1 @ControllerAdvice
 2 @Slf4j
 3 public class ExceptionCatch {
 4     @ExceptionHandler(CustomerException.class)
 5     public ResponseResult customerException(CustomerException customerException){
 6 
 7         ResultCode resultCode = customerException.getResultCode();
 8         ResponseResult responseResult = new ResponseResult(resultCode);
 9     return  responseResult;
10     }

 

4CustomerException类(抛出的异常类)
public class CustomerException extends RuntimeException {
    private ResultCode resultCode;
    public ResultCode getResultCode(){
        return resultCode;

    }
    public CustomerException(ResultCode resultCode){
        super("错误代码"+resultCode.code()+"错误信息:"+resultCode.message());
        this.resultCode =resultCode;

    }
}

(二)系统级别的例子

抓取不可预知的异常,信息用log输出,

@Slf4j

后期方便定位问题,info。warning,error日志的常见级别

 1 @ControllerAdvice
 2 @Slf4j
 3 public class ExceptionCatch {
 4  
 5 @ExceptionHandler(Exception.class)
 6     public ResponseResult exception(Exception exception){
 7         log.error(exception.getMessage());
 8         return null;
 9 
10 }
11 
12 }

特定异常添加到特定map中(谷歌提供的)

ImmutableMap
//全局异常抓取类
@ControllerAdvice //增强controller
@Slf4j
public class ExceptionCatch {

    //ImmutableMap 线程安全,声明之后内容不可变
    private static ImmutableMap<Class<? extends Throwable>,ResultCode> EXCEPTIONS;

    protected static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder = ImmutableMap.builder();

    //抓取自定义异常(可预知异常)
    @ExceptionHandler(CustomerException.class)
    @ResponseBody
    public ResponseResult customerException(CustomerException customerException){
        //给用户返回友好信息
        ResultCode resultCode = customerException.getResultCode();

        ResponseResult responseResult = new ResponseResult(resultCode);
        return responseResult;
    }

    //抓取不可预知异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception){

        log.error(exception.getMessage());

        if (EXCEPTIONS == null){
            EXCEPTIONS = builder.build();
        }
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode == null){
            return new ResponseResult(CommonCode.SERVER_ERROR);
        }else{
            return new ResponseResult(resultCode);
        }

    }

    static {
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALIDATE_PARAMS);
    }
}

从map中找,有,返回key对应的value,没有的话返回固定的友好提示:服务器繁忙。

おすすめ

転載: www.cnblogs.com/fengtangjiang/p/11111200.html