SpringBoot基础-错误异常处理统一办法

  1. 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";
        }
         
    }
  2.  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;
        }
     
    }
  3.  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>
  4. 重启测试
    按理说会自动重启,因为配置了热部署
    http://127.0.0.1:8080/hello
    





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值