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)
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.message}"></p>
錯誤頁面爲:<p th:text="${url}"></p>
</body>
</html>
3 隨便在contoller裏拋出一個錯誤,例如 :
4 結果展示:
根據慕課網學習整理