SpringBoot-10-全局异常

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-10-全局异常

异常统一处理

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

  • 创建全局异常类:通过使用**@RestControllerAdvice+@ExceptionHandler**进行全局异常处理,就不需要在所有的Controller中定义异常。代码如下:

    @RestControllerAdvice
    public class GlobalExceptionHandler {
        public static final String ERROR_VIEW = "error";
        @ExceptionHandler(value = Exception.class)
        public ModelAndView exceptionError(HttpServletRequest reqException ethrows 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页面展示,放在srcmainresourcestemplates目录下代码如下:

    <!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,显示结果如下:

SpringBoot-10-全局异常

自定义异常处理:

  • 创建一个统一的异常处理实体:
@Data
public class Result<Timplements 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<StringexceptionError(HttpServletRequest reqGlobalException ethrows 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,可以得到如下返回内容:

SpringBoot-10-全局异常

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

SpringBoot-10-全局异常


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


原文始发于微信公众号(springboot葵花宝典):SpringBoot-10-全局异常

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/184432.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!