栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

Spring Boot:异常处理机制

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot:异常处理机制

最近公司的项目正在重构,我正好担任了这个重任,采用的是Spring Boot和Docker的方式,因此很长时间没在更新博客了,在接下一段时间中我会将Spring Boot构建项目这块持续更新,最终能构建一个完整的Spring Boot基础架构,并开源出来分享给大家,Spring Cloud的那个项目在之后还会持续更新的。

在Spring Boot中,当最终有未处理的异常抛出的时候,Servlet容器仍然会发送/error请求,但是和spring mvc不同的是,Spring Boot提供了内置的BasicErrorController处理全局的错误信息,不需要任何其他的配置。

下面通过一个简单的例子验证一下Spring Boot中默认的异常处理流程:

  1. 首先在SysUserController中映射index请求,接口中什么都不做,仅抛出一个RuntimeException异常。

@Controller@RequestMapping("user")public class SysUserController {    
    @RequestMapping("/")    @ResponseBody
    public String index(){        throw new RuntimeException("page error!");
    }

}

请求http://localhost:8080/user/页面出现如下的效果

image.png


我们可以从图中看到默认Spring Boot有一个请求/error的mapping,实际上,Spring Boot已经为我们提供了/error请求的controller,它就是BasicErrorController。


BasicErrorController的源码如下:

@Controller@RequestMapping({"${server.error.path:${error.path:/error}}"})public class BasicErrorController extends AbstractErrorController {    // ... 省略构造函数
    public String getErrorPath() {        return this.errorProperties.getPath();
    }    @RequestMapping(
        produces = {"text/html"}
    )    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = this.getStatus(request);
        Map model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);        return modelAndView != null ? modelAndView : new ModelAndView("error", model);
    }    @RequestMapping
    public ResponseEntity> error(HttpServletRequest request) {
        Map body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = this.getStatus(request);        return new ResponseEntity(body, status);
    }    protected ErrorProperties getErrorProperties() {        return this.errorProperties;
    }    
    // ... 省略其他方法}
  • BasicErrorController处理{error.path:/error}请求。意思是:

    • 如果在application.properties中设置了server.error.path,就映射该值;

    • 而如果error.path有值就映射该值

    • 最后否则映射/error
      所以,优先级=> server.error.path>error.path>/error,可以通过修改server.error.path和error.path让BasicErrorController不再处理error请求。

  • BasicErrorController有errorHtml和error两种不同的处理接口处理请求,其errorHtml特指http请求中accept属性值为text/html的请求。

如果请求的返回类型不同,可以为一个请求通过设置produces指定特定的返回类型。

自定义错误页面

Spring Boot默认的错误页面显然不能满足开发的正常需求,通过在src/main/resources/templates文件夹中添加error.html错误页面实现自定义错误信息。还可以通过在src/main/resources/templates/error中添加404.html等以http错误码开头的页面实现不同http错误状态的不同展现。结构如下图:

image.png


当我们再次访问http://localhost:8080/user/页面出现如下的效果:

image.png


统一异常处理

前文说过,/error请求的触发前提是系统中抛出的异常到最终都没有被处理掉,Spring Boot可以通过@ControllerAdvice和@ExceptionHandler实现捕获系统中的异常**,需要注意的是,如果@ControllerAdvice中如果有其他异常没有捕获到,最终仍然会通过BasicErrorController处理这些异常。

统一异常处理部分代码如下:

@ControllerAdvice("com.hrabbit.admin")@Order(-1)@Slf4jpublic class GlobalExceptionHandler {    
    @ExceptionHandler(SysUserException.class)    @ResponseStatus(HttpStatus.UNAUTHORIZED)    public String sysUserExceptionHandler(Model model,SysUserException ex) {
        model.addAttribute("msg",ex.getMessage());        return "login";
    }    
    @ExceptionHandler(UnauthorizedException.class)    @ResponseBody
    public baseResponse shiroExceptionHandler(HttpServletResponse response, Exception ex) {
        log.error(ex.getMessage(),ex);        return new baseResponse(CommonConstants.SHESHU_USER_SHIRO_INVALID_CODE, "对不起,你没有此权限!");
    }    
    @ExceptionHandler(AuthenticationException.class)    @ResponseStatus(HttpStatus.UNAUTHORIZED)    public String unAuth(AuthenticationException e,Model model) {
        model.addAttribute("msg","请检查用户权限!");        return "/login";
    }
}



作者:hrabbits
链接:https://www.jianshu.com/p/20aa608c4f09


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235317.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号