5.SPRINGBOOT 错误异常处理统一办法

HelloController

修改HelloController,使得访问/hello一定会产生异常: some exception
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.how2java.springboot.web;
import java.text.DateFormat;
import java.util.Date;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
  
@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";
    }
     
}
 步骤 4 : 

GlobalExceptionHandler

新增加一个类GlobalExceptionHandler,用于捕捉Exception异常以及其子类。
捕捉到之后,把异常信息,发出异常的地址放进ModelAndView里,然后跳转到 errorPage.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.how2java.springboot.exception;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
 
@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;
    }
 
}
 步骤 5 : 

errorPage.jsp

errorPage.jsp 格式化一下,稍微好看点显示这些异常信息
1
2
3
4
5
6
7
8
9
10
11
12
<%@ 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>
    
 步骤 6 : 

重启测试

 

 
按理说会自动重启,因为配置了热部署
 
http://127.0.0.1:8080/hello
 
重启测试
http://download.how2j.cn/1646/springboot.rar

posted on 2019-01-04 15:49  我是司  阅读(260)  评论(0)    收藏  举报

导航