利用try catch将与业务无关的代码隔离

在实际开发过程中,我们可能会记录请求参数,返回参数值,以及接入第三方组件进行业务的监控等等,这些请求,都可能有异常,此时,需要通过try/catch 将,异常进行捕获并记录,而不要影响已有的业务。
举个例子:
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
    try {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        if (StringUtils.isNotBlank(uri)) {
            Cat.logMetricForCount(RestFulURIUtil.getRestFulURI(uri)); // 统计所有请求的访问次数
        }
    } catch (Exception e) { //辅助业务功能不能影响到主业务,必须进行异常捕获
        log.error("error is:{}.", e);
    }
}
上述的代码中,我将业务的请求接入监控中,而对于第三方Cat我们认为是不可靠的,比如:Cat.logMetricForCount()函数可能报异常,此时,通过try/catch进行捕获,不会影响正常业务的执行。

猜你喜欢

转载自blog.csdn.net/timchen525/article/details/79888599