SpringBoot异常处理

1. 配置全局异常和自定义异常

  1. 异常处理类(包括全局和自定义)
@RestControllerAdvice
public class CustomExtHandler {

    /**
     * 处理全局异常
     * 返回json数据,由前端去判断加载什么页面(推荐)
     */
    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e, HttpServletRequest request) {

        log.error("url [{}], msg [{}]", request.getRequestURL(), e.getMessage());

        Map map = new HashMap<>(3);
        map.put("code", 500);
        map.put("msg", e.getMessage());
        map.put("url", request.getRequestURL());
        return map;
    }

    /**
     * 处理自定义异常
     * 返回json数据,由前端去判断加载什么页面(推荐)
     */
    @ExceptionHandler(value = MyException.class)
    Object handleMyException(MyException e, HttpServletRequest request) {

        log.error("url [{}], msg [{}]", request.getRequestURL(), e.getMessage());

        Map map = new HashMap<>(3);
        map.put("code", e.getCode());
        map.put("msg", e.getMsg());
        map.put("url", request.getRequestURL());
        return map;
    }
}
  1. 自定义异常类
@Getter
@Setter
public class MyException extends RuntimeException {
     //状态码
    private String code;
     //错误信息
    private String msg;

    public MyException(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}

2.返回自定义页面

  1. 创建自定义页面位置,位置如下图:



    
    Error Page

页面加载异常

error.html位置
  1. 引入thymeleaf依赖

    org.springframework.boot
    spring-boot-starter-thymeleaf

  1. 异常处理类
@RestControllerAdvice
public class CustomExtHandler {
    /**
     * 处理自定义异常
     * 进行页面跳转
     */
    @ExceptionHandler(value = MyException.class)
    Object handleMyException(MyException e, HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error.html");
        modelAndView.addObject("msg", e.getMessage());
        return modelAndView;
    }
}

你可能感兴趣的:(SpringBoot异常处理)