SpringBoot学习-part28 定制错误数据

    技术2025-01-07  17

    自定义异常

    public class UserNotExistException extends RuntimeException { public UserNotExistException(){ super("用户不存在"); } }

    5xx.html 页面输出异常信息

    <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"> <h1>5xx-----status:[[${status}]]</h1> <h2>5xx-----timestamp:[[${timestamp}]]</h2> <h2>5xx-&#45;&#45;&#45;&#45;exception:[[${exception}]]</h2> <h2>5xx-&#45;&#45;&#45;&#45;exception.message:[[${exception.message}]]</h2> </main>

    处理请求产生异常

    @ResponseBody @RequestMapping("/hello") public String hello(@RequestParam("user") String user){ if("a".equals(user)){ System.out.println("we should throw new UserNotExistException()"); throw new UserNotExistException(); } return "helloworld"; }

    输出结果

    页面收到的expcetion为null,没有接受到exception

    解决5xx.html页面未收到异常:

    更改SpringBoot默认配置

    默认配置

    /** * When to include the "trace" attribute. */ private IncludeStacktrace includeStacktrace = IncludeStacktrace.NEVER; /** * When to include "message" attribute. */ private IncludeAttribute includeMessage = IncludeAttribute.NEVER;

    在全局配置文件 application.properties 覆盖默认配置

    server.error.include-exception=true server.error.include-message=always

    5xx.html成功收获异常

    自定义异常处理器

    @ControllerAdvice public class MyExceptionHandler { @ResponseBody @ExceptionHandler(UserNotExistException.class) public Map<String,Object> handleException(Exception e){ Map<String,Object> map = new HashMap<>(); //存放自己的错误代码 map.put("code","user.notexist"); map.put("message",e.getMessage()); return map; } }

    PostMan测试异常处理器

    浏览器页面异常效果

    异常显示如何自适应

    当前无论浏览器还是非浏览器,返回的都是Json数据,没有达到自适应效果

    使用转发能否达到自适应

    //@ResponseBody @ExceptionHandler(UserNotExistException.class) public String handleException(Exception e){ Map<String,Object> map = new HashMap<>(); //存放自己的错误代码 map.put("code","user.notexist"); map.put("message",e.getMessage()); return "forward:/error"; }

    为什么浏览器还是空白页面?

    通过解析error的status_code 来决定跳转的视图名

    传入HttpServletRequest,设置状态码

    修改自定的异常处理,传入HttpServletRequest,并设置错误状态码

    //@ResponseBody @ExceptionHandler(UserNotExistException.class) public String handleException(Exception e, HttpServletRequest request){ Map<String,Object> map = new HashMap<>(); request.setAttribute("javax.servlet.error.status_code",500); //存放自己的错误代码 map.put("code","user.notexist"); map.put("message",e.getMessage()); return "forward:/error"; }

    测试

    携带定制的错误数据

    DefaultErrorAttributes 默认进行错误数据处理

    DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered

    在ErrorMvcAutoConfiguration中:

    @Bean @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) public DefaultErrorAttributes errorAttributes() { return new DefaultErrorAttributes(); }

    注意到使用了@ConditionalOnMissingBean,所以我们可以自己向容器中注入自定义的ErrorArributes,来修改默认行为。

    @Component public class MyErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map<String, Object> attributes = super.getErrorAttributes(webRequest, options); attributes.put("company","EzerbelCN"); return attributes; } }

    测试

    添加扩展的异常数据信息

    //@ResponseBody @ExceptionHandler(UserNotExistException.class) public String handleException(Exception e, HttpServletRequest request){ Map<String,Object> map = new HashMap<>(); request.setAttribute("javax.servlet.error.status_code",500); //存放自己的错误代码 map.put("code","user.notexist"); map.put("message",e.getMessage()); request.setAttribute("ext",map); return "forward:/error"; }

    解析扩展的异常数据信息

    @Component public class MyErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map<String, Object> attributes = super.getErrorAttributes(webRequest, options); attributes.put("company","EzerbelCN"); // SCOPE_REQUEST = 0 // SCOPE_SESSION = 1 // 前面ext被存在了request域中,所以要去request域 scope = 0 中获取 Map<String,Object> ext = (Map<String, Object>) webRequest.getAttribute("ext",0); if (ext != null) { attributes.put("ext",ext); } return attributes; } }

    异常显示页面

    <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"> <h1>5xx-----status:[[${status}]]</h1> <h2>5xx-----timestamp:[[${timestamp}]]</h2> <h2>5xx-----exception:[[${exception}]]</h2> <h2>5xx-----message:[[${message}]]</h2> <h2>5xx-----ext.code:[[${ext.code}]]</h2> <h2>5xx-----ext.message:[[${ext.message}]]</h2> </main>

    Processed: 0.008, SQL: 9