简易异常处理实现(AOP+注解)
- 增加注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionResolve {
String code() default "null";
String message() default "null";
}
- 增加切面
@Slf4j
@Aspect
@Component
public class ExceptionAspect {
@Around("@annotation(exceptionResolve)")
public Object exceptionHandle(ProceedingJoinPoint joinPoint, ExceptionResolve exceptionResolve){
try {
return joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
// 返回值封装
Map<String, String> result = new HashMap<>(2);
result.put("code", exceptionResolve.code());
result.put("message", exceptionResolve.message() + throwable.getMessage());
return result;
}
}
}
- 增加测试
@GetMapping("/test")
@ExceptionResolve(code="000", message = "ERROR")
public Object test(){
System.out.println(1/0);
return "SUCCESS";
}
- 返回结果
{
"message": "ERROR/ by zero",
"code": "000"
}