1.添加异常,在HelloController代码段内,添加异常,方便进行测试。
@RequestMapping("/hello")
public String hello(Model m) throws Exception {
m.addAttribute("now", DateFormat.getDateTimeInstance().format(new Date()));
if(true){
throw new Exception("some exception");
}
return "hello";
}
}
2.新增GlobalExceptionHandle,用于捕获Exception异常及其子类,且将其跳转到errorPage页面内。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", req.getRequestURL());
mav.setViewName("errorPage");
return mav;
}
}
3.errorPage页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<div style="500px;border:1px solid lightgray;margin:200px auto;padding:80px">
系统 出现了异常,异常原因是:
${exception}
<br><br>
出现异常的地址是:
${url}
</div>
4.打开http://127.0.0.1:8080/hello页面,进行测试
![image-20201109164737354](https://i.loli.net/2020/11/17/T2LycQzaWx5gurM.png)