SpringBoot配置全域性的異常捕獲-web頁面跳轉
阿新 • • 發佈:2018-12-20
一 定義控制器
package com.imooc.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.imooc.pojo.IMoocJSONResult; @Controller @RequestMapping("err") public class ErrorController { @RequestMapping("/error") public String error() { int a = 1 / 0; return "thymeleaf/error"; } }
二 定義錯誤處理類
package com.imooc.exception; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import com.imooc.pojo.IMoocJSONResult; @ControllerAdvice public class IMoocExceptionHandler { public static final String IMOOC_ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public Object errorHandler(HttpServletRequest reqest, HttpServletResponse response, Exception e) throws Exception { e.printStackTrace(); ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", reqest.getRequestURL()); mav.setViewName(IMOOC_ERROR_VIEW); return mav; } }
三 定義錯誤頁面模板
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title>捕獲全域性異常</title> </head> <body> <h1 style="color: red">發生錯誤:</h1> <div th:text="${url}"></div> <div th:text="${exception.message}"></div> </body> </html>
四 測試