1 SpringBoot配置全局的異常捕獲-web頁面跳轉

1 在src/main/java/com/imooc 新建exception包,在該包下新建MyExceptionHandler.java內容如下:

package com.imooc.contoller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
package com.imooc.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice //表示這是一個助手類,當程序發生異常時,會被這個類捕獲
public class MyExceptionHandler {
    public static final String ERROR_VIEW="error";
//@ExceptionHandler (value = Exception.class) 表示對Exception異常進行捕獲
    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest request, HttpServletResponse response,Exception e) throws Exception{
        ModelAndView mav=new ModelAndView();
        mav.addObject("exception",e);
        mav.addObject("url",request.getRequestURI());
        mav.setViewName(ERROR_VIEW);
        return mav;
    }
}

2 在src/main/resources/templates文件夾先新建error.html,內容如下:

          <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>捕獲全局異常</title>
</head>
<body><h1 style="color:red">發生錯誤:</h1>

 <!--錯誤類爲:<p th:text="${exception}"></p>-->
 錯誤信息爲:<p th:text="${exception.message}"></p>
 錯誤頁面爲:<p th:text="${url}"></p>
</body>
</html>

3 隨便在contoller裏拋出一個錯誤,例如 :

在這裏插入圖片描述

4 結果展示:

在這裏插入圖片描述

根據慕課網學習整理

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