现状
开发对外HSF服务时,实现逻辑中往往会有异常处理和打印出入参的操作。处理步骤一般为打印入参、执行业务逻辑、处理异常、打印出参。标记红色的都是比较固定的逻辑,这部分往往是重复的。针对异常处理,如果不同的方法想使用统一的异常处理逻辑,一般的做法是拷贝原来的代码,复制一份然后修改。这种做法会导致重复,如果想为异常处理加一些通用的逻辑,不得不将每个方法都修改一遍,很容易遗漏。
/**
* @Author canglong
* @Date 2022/11/7
*/
@Slf4j
public class FooService {
String method1(String arg) {
log.info(arg);
String res = null;
try {
//do some calculate
res = bizLogic(arg);
} catch (Exception e) {
log.error("bizLogic" + arg, e);
}
log.info(res);
return res;
}
String method2(String arg) {
log.info(arg);
String res = null;
try {
//do some calculate
res = bizLogic(arg);
} catch (Exception e) {
log.error("bizLogic" + arg, e);
}
log.info(res);
return res;
}
String method3(String arg) {
log.info(arg);
String res = null;
try {
//do some calculate
res = bizLogic(arg);
} catch (Exception e) {
log.error("bizLogic" + arg, e);
}
log.info(res);
return res;
}
String bizLogic(String arg) {
return "bizLogic";
}
}
目标
基于以上的现状,我开发了一个小工具来解决上面的问题。主要有以下两个功能。
1、支持通过声明的方式开启或关闭出参入参打印,不用写重复的代码
2、支持全局的异常处理,同时也支持自定义的异常处理逻辑。
用法
第一步引入starter
<dependency>
<groupId>com.xxx.kits</groupId>
<artifactId>diagnosis-spring-boot-starter</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
第二步使用注解修饰指定的方法
使用@EnableDebug修饰的方法会打印出参、入参、耗时。通过EnableDebug.rt属性可以控制是否打印耗时日志。默认开启。通过@HandleException指定全局异常处理器。这个异常处理器是业务自定义的,负责执行业务定制的异常处理逻辑。异常处理器的发现,是通过spring容器查找的。所以,异常处理器需要被声明为Spring Bean,即需要被@Component修饰。
public class FooService {
@EnableDebug
@HandleException(handler = FooExceptionHandler.class)
String method1(String arg) {
String res = bizLogic(arg);
return res;
}
@EnableDebug(rt = false)
String method2(String arg) {
String res = bizLogic(arg);
return res;
}
String bizLogic(String arg) {
return "bizLogic";
}
}
自定义异常处理器
@Slf4j
@Component
public class FooExceptionHandler implements ExceptionHandler<String> {
@Override
public String handle(Throwable throwable, Object[] args) {
log.error(JSON.toJSONString(args), throwable);
return "defaultVal";
}
}
其他配置
关闭调试日志
如果调试完成了,需要在线上关闭调试日志,则在应用配置文件中设置
tool.kits.diagnosis.debug.enable=false
即可。一般在预发开启调试日志,在线上关闭调试日志。
注解作用范围
@EnableDebug和@HandleException如果修饰在类上,则类中的所有方法都生效。如果修饰在方法上,则被修饰的方法生效。针对@HandleException,可以在类上声明通用的异常处理器,然后在有特定需求的方法上指定自定义的异常处理器。例如:
@HandleException(handler = FooExceptionHandler.class)
public class FooService {
@EnableDebug
String method1(String arg) {
String res = bizLogic(arg);
return res;
}
@EnableDebug(rt = false)
@HandleException(handler = Method2SpecificExceptionHandler.class)
String method2(String arg) {
String res = bizLogic(arg);
return res;
}
String bizLogic(String arg) {
return "bizLogic";
}
}
@Component
public class Method2SpecificExceptionHandler implements ExceptionHandler<String> {
@Override
public String handle(Throwable throwable, Object[] objects) {
return "specific logic";
}
}