四时宝库

程序员的知识宝库

SpringBoot-10-全局异常(springboot全局变量)

SpringBoot-10-全局异常

我们在做后台开发的时候,出现错误是很正常的,SpringBoot异常报错有一默认的映射:/error,当出现错误的时候,SpringBoot会转到该请求中,并且这个请求还有一个全局的错误页面来展示这个错误。

新建一个SpringBoot项目,代码如下:

@Controller
public class TestController {
    @GetMapping("/test")
    public String test() throws  Exception{
       int a=1/0;
       return "test";
    }
}

然后访问http://localhost:8080/test,就会出现以下报错的页面,这个页面就是默认的error页面

异常统一处理

虽然SpringBoot存在默认的error错误页,但是显示的信息不够友好,需要我们对其进行修改,修改过程如下:

  • 创建全局异常类:通过使用@RestControllerAdvice+@ExceptionHandler进行全局异常处理,就不需要在所有的Controller中定义异常。代码如下:
  • @RestControllerAdvice
    public class GlobalExceptionHandler {
    public static final String ERROR_VIEW = "error";
    @ExceptionHandler(value = Exception.class)
    public ModelAndView exceptionError(HttpServletRequest req, Exception e) throws Exception{
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", e);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName(ERROR_VIEW);
    return mav;
    }
    }

  • @RestControllerAdvice用于获取Controller层的异常,并返回JSON格式。
  • @ExceptionHandler是一种统一处理异常的注解,用于减少代码重复率,降低复杂度。
  • 实现自定义的error.html页面展示,放在src\main\resources\templates目录下代码如下:
  • <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
    <head lang="en">
    <meta charset="UTF-8" />
    <title>异常统一处理</title>
    </head>
    <body>
    <h1>异常统一处理</h1>
    <div >
    错误请求地址:
    <label th:text="${url}"></label><br/>
    错误信息:
    <label th:text="${exception.message}"></label><br/>
    </div>
    </body>
    </html>
  • 启动项目,访问http://localhost:8080/test,显示结果如下:

自定义异常处理:

  • 创建一个统一的异常处理实体:
@Data
public class Result<T> implements Serializable {
    public static final Integer SUCCESS = 200;
    public static final Integer FAILURE_ERROR = 404;
    private static final long serialVersionUID = 1L;
    /**
     * 代码
     */
    private int code;
    /**
     * 信息
     */
    private String msg;
    /**
     * 时间
     */
    private long time;
    /**
     * 数据实体
     */
    private T data;
}
  • 创建GlobalException自定义的全局异常处理类
public class GlobalException extends Exception{
    public GlobalException(String msg){
        super(msg);
    }
}
  • 在Controller层创建一个测试方法
    @GetMapping("/testexception")
    public String testexception() throws GlobalException {
        throw new GlobalException("发生test错误2");
    }
  • 修改GlobalException异常创建对应的处理
@RestControllerAdvice
public class GlobalExceptionHandler {
    public static final String ERROR_VIEW = "error";
    @ExceptionHandler(value = GlobalException.class)
    public  Result<String> exceptionError(HttpServletRequest req, GlobalException e) throws Exception{
//        ModelAndView mav = new ModelAndView();
//        mav.addObject("exception", e);
//        mav.addObject("url", req.getRequestURL());
//        mav.setViewName(ERROR_VIEW);
        Result<String> result = new Result<>();
        result.setTime( System.currentTimeMillis());
        result.setMsg(e.getMessage());
        result.setCode(404);
        result.setData(req.getRequestURL().toString());
        return result;
    }
}
  • 启动应用,访问:http://localhost:8080/testexception,可以得到如下返回内容:

如果您觉得本文不错,欢迎关注支持,您的关注是我坚持的动力!

原创不易,转载请注明出处,感谢支持!如果本文对您有用,欢迎转发分享!

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接