springboot

11.springboot全局异常处理

2020-03-30  本文已影响0人  0f701952a44b
1.异常处理

public class CustomExceptionHandler {
    /**
     * 统一异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    Object handlerException(Exception e,HttpServletRequest request) {
        Map<String,Object> map =  new HashMap<String,Object>();
        map.put("code", "100");
        map.put("msg", e.getMessage());
        map.put("request", request.getRequestURL());
        return map;
    }
    /**
     * 处理自定义异常,返回异常对应的错误页面
     * @param e
     * @return
     */
    @ExceptionHandler(value = MyException.class)
    Object handleMyException(MyException e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error.html");
        modelAndView.addObject("msg", e.getMsg());
        System.out.println(e.getMsg());
        return modelAndView;
    }
    /**
     * 处理自定义异常,返回错误信息
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = MyException2.class)
    Object handleMyException2(MyException2 e,HttpServletRequest request) {
        Map<String,Object> map =  new HashMap<String,Object>();
        map.put("code", "100");
        map.put("msg", e.getMsg());
        map.put("request", request.getRequestURL());
        return map;
    }
}
2.MyException、MyException2根据需求自己定义
public class MyException extends RuntimeException{
    private String code;
    private String msg;
    
    public MyException(String code, String msg) {
        super();
        this.code = code;
        this.msg = msg;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    
}
3.异常跳转错误页面

1)需要引入依赖

 <!-- 使用Thymeleaf视图构建MVC Web应用程序的入门 -->
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2)error.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>springboot html test</title>
</head>
<body>
    404 error!
</body>
</html>

4.测试controller

@RestController
public class ExceptionTestController {
    @GetMapping("/test/exp")
    Object TestException() {
        System.out.println(1/0);
        return new User("1", "lxh", "159", new Date());
    }
    @GetMapping("/test/myexp")
    Object TestMyException() {
        throw new MyException("101", "my exception test");
    }
    @GetMapping("/test/myexp2")
    Object TestMyException2() {
        throw new MyException2("102", "my exception2 test");
    }
}
上一篇下一篇

猜你喜欢

热点阅读