SpringBoot | 异常配置源码分析

24 篇文章 14 订阅
12 篇文章 5 订阅

springboot的异常处理采用的其实就是spring的异常处理机制,只是在spring的基础之上多了一个统一异常出口。
首先看一下spring异常处理入口肯定是spring接受请求的类中:DispatcherServlet类
这里写图片描述

在真实请求执行结束之后,进行处理结果:processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException),跟进该方法:

这里写图片描述

上图中如果异常不为空,则开始解析异常,如果为ModelAndViewDefiningException类型异常,则直接渲染调用下面的render方法渲染异常,否则进入下面的异常解析方法:

这里写图片描述

上图我们看到有 this.handlerExceptionResolvers 集合有两个元素,一个是DefaultErrorAttributes,主要是用来存储异常信息,在构造返回结果的时候会到该对象中取。另一个是HandlerExceptionResolverComposite,可以理解为容器,它并不会解析具体的异常,而是调用其他的异常解析器处理异常。

继续跟进 resolveException 方法。

这里写图片描述

可以看到该类中定义了一个属性:

private List<HandlerExceptionResolver> resolvers;

该集合中存放了HandlerExceptionResolver的其他子类:
0 = {ExceptionHandlerExceptionResolver@8800}
1 = {ResponseStatusExceptionResolver@8801}
2 = {DefaultHandlerExceptionResolver@8802}

1) ExceptionHandlerExceptionResolver 是我们用到最多的异常解析类,主要配合@ExceptionHandler一起使用,该注解所标注的异常类都会被该解析类拿到,进行匹配。匹配流程后面通过源码详细介绍。

2) ResponseStatusExceptionResolver 是用来标识我们自定义的异常,配合@ResponseStatus一起使用。

@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends BaseException {
}

当抛出对应的异常时,会解析成对应的状态码和错误信息返回给调用方。

3) DefaultHandlerExceptionResolver 是默认的解析类,用来兜底。当前面的解析类执行后没有返回时,才执行该解析类。

三个解析类,优先级由高到低,依次执行。


下面详细分析 ExceptionHandlerExceptionResolver 具体的解析流程。

首先跟进该类的入口方法 resolveException,会调用抽象类中的解析方法:
这里写图片描述

抽象类中并没有具体的逻辑,通过方法名可以知道,这里采用了模板模式,具体调用的实际方法为子类中的方法,如下图:

这里写图片描述

先来看第一行代码:

ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception);

第一行是构造ServletInvocableHandlerMethod 对象,该对象是异常解析器解析后的结果,封装了具体的执行逻辑。来看一下该对象是如何获得的。

这里写图片描述

上面 exceptionHandlerAdviceCache 对象中存储的是 exceptionHandler集合,也就是ResponseEntityExceptionHandler的子类。具体是我们自己定义:

/**
 * Created by zhangshukang on 2017/10/06.
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
}

需要注意的是当定义多个handler的时候,要注意handler的执行顺序,只要匹配到对应的异常,就会返回。

继续跟进 中的 resolveMethod 方法,会找到具体的异常匹配方法,如下:

这里写图片描述

    Iterator var3 = this.mappedMethods.keySet().iterator();

        while(var3.hasNext()) {
            Class mappedException = (Class)var3.next();
            if(mappedException.isAssignableFrom(exceptionType)) {
                matches.add(mappedException);
            }
        }

这里敲黑板了。
mappedMethods 集合是我们定义的所有的异常集合,mappedException.isAssignableFrom(exceptionType),表面只要我们定义的异常类型和抛出的类型一致,或者是抛出的异常的父类,则匹配成功,返回异常对象。
所以我们在定义handlers中的异常时,上层异常类应该定义在下面,用来兜底。

一些常见的异常定义如下:

 @ExceptionHandler(BadRequestException.class)
    @ResponseBody
    public ResponseEntity<MessageVo> handleBadRequestException(HttpServletRequest request, HttpServletResponse response, BadRequestException ex) {
        log.error(ex.getMessage(), ex);
        return new ResponseEntity<>(ex.getMessageList(), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseEntity<MessageVo> handleBusinessException(HttpServletRequest request, HttpServletResponse response, BusinessException ex) {
        log.error(ErrorLogInfo.build(ex.getSrcClass(), systemName, ex.getErrorCode(), ex.getMessage()).toJson());
        Throwable orgEx = ex.getOriginalException();
        if (orgEx != null)
            log.error(orgEx.getMessage(), orgEx);
        else
            log.error(ex.getMessage(), ex);

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessageList());
    }

注意:Exception 类 一定要放在最下面。

到这里,解析流程基本结束了,拿到ServletInvocableHandlerMethod 后,就执行具体的返回逻辑了。


springboot异常不同点

springboot异常处理只是在spring异常机制上优化了错误路径访问。发生异常的时候会自动把请求转到/error,SpringBoot内置了一个BasicErrorController对异常进行统一的处理,当然也可以自定义AbstractErrorController的子类,来覆盖BasicErrorController。在自己定义的类中,可以自己定义错误路径。

自定义示例:

@Controller
@Slf4j
public class GlobalExceptionController extends AbstractErrorController {
    private final ErrorProperties errorProperties;

    public GlobalExceptionController(){
        this(new DefaultErrorAttributes());
    }
    public GlobalExceptionController(ErrorAttributes errorAttributes) {
        this(errorAttributes, new ErrorProperties());
    }
    public GlobalExceptionController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        super(errorAttributes);
        Assert.notNull(errorProperties, "ErrorProperties must not be null");
        this.errorProperties = errorProperties;
    }

    private static final String PATH = "/error";

    @Override
    public String getErrorPath() {
        return PATH;
    }

    @RequestMapping("${server.error.path:${error.path:/error}}")
    @ResponseBody
    public ResponseEntity error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        String errMsg = getErrorMessage(request) != null ? getErrorMessage(request) : (String)body.get("message");
        log.error("url:{},error:{},message:{}", body.get("path"), body.get("error"), errMsg);
        if(status == HttpStatus.NOT_FOUND) {
            NotFoundException ne = new NotFoundException(BaseException.ERR_9996, this);
            return new ResponseEntity(ne.getMessageList(), status);
        } else {
            MessageVo msg = new MessageVo();
            msg.addMessageObj(BaseException.ERR_9999, errMsg, null);
            return new ResponseEntity(msg, status);
        }
    }

    protected ErrorProperties getErrorProperties() {
        return this.errorProperties;
    }

    protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
        ErrorProperties.IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
        if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
            return true;
        }
        if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
            return getTraceParameter(request);
        }
        return false;
    }

    private String getErrorMessage(HttpServletRequest request) {
        final Throwable exc = (Throwable) request.getAttribute("javax.servlet.error.exception");
        return exc != null ? exc.getMessage() : null;
    }
}

上面类中用到了 ErrorAttributes对象,该对象存储了异常的详细信息。具体该对象什么时候存储的异常信息,前面已经提到了这一点了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值