- HelloController
修改HelloController,使得访问/hello一定会产生异常: some exception@Controller public class 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"; } }
- GlobalExceptionHandler
新增加一个类GlobalExceptionHandler,用于捕捉Exception异常以及其子类。
捕捉到之后,把异常信息,发出异常的地址放进ModelAndView里,然后跳转到 errorPage.jsp@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; } }
- errorPage.jsp
errorPage.jsp 格式化一下,稍微好看点显示这些异常信息<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <div style="width:500px;border:1px solid lightgray;margin:200px auto;padding:80px"> 系统 出现了异常,异常原因是: ${exception} <br><br> 出现异常的地址是: ${url} </div>
- 重启测试
按理说会自动重启,因为配置了热部署http://127.0.0.1:8080/hello
SpringBoot基础-错误异常处理统一办法
最新推荐文章于 2022-02-15 18:22:11 发布