SpringMVC全局異常————初識HandlerExceptionResolver

SpringMVC提供了統一的異常處理

這裏只提供SpringMVC全局異常處理的簡單應用,並不包含其原理,文中如有不妥,還請前輩們不吝賜教

SpringMVC提供了統一的異常處理,接口HandlerExceptionResolver,自定義類實現HandlerExceptionResolver接口,重寫resolveException方法。使用此方法可以在Controller層不拋出異常的情況,自動捕獲異常,進行處理,相關步驟如下:

CustomExceptionResolver

//全局異常處理器
public class CustomExceptionResolver implements HandlerExceptionResolver {

    //系統拋出的異常
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //handler就是處理器適配器要執行的Handler對象(只有method)
        //解析出異常類型。
        System.out.println("異常");
        CustomException customException = null;

        //如果該 異常類型是系統 自定義的異常,直接取出異常信息,在錯誤頁面展示。
        if (e instanceof CustomException){
            customException = (CustomException) e;
        }else{

            //如果該 異常類型不是系統 自定義的異常,構造一個自定義的異常類型(信息爲“未知錯誤”)。
            customException = new CustomException("發生了一個未知的錯誤,請重試");
        }

        //錯誤信息
        String message = customException.getMessage();
        //將錯誤信息傳到頁面,並且指向錯誤頁面
        return new ModelAndView("redirect:/Index.html","message",message);
    }
}

CustomException

//創建自定義異常
public class CustomException extends Exception {

    //異常信息
    private String message;

    public CustomException(String message) {
        super(message);
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

SpringMVC的配置文件中注入

<!--自定義異常-->
    <bean class="com.hqyj.IoT.exception.CustomExceptionResolver"/>

如果有興趣,可以去看看,Spring中HandlerExceptionResolver部分的源碼,想要了解其原理,還是看源碼比較好。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章