Spring AOP统一异常处理
简介
在Controller层,Service层,可能会有很多的try catch代码块。这将会严重影响代码的可读性、“美观性”。怎样才可以把更多的精力放在业务代码的开发,同时代码变得更加简洁?既然业务代码不显式地对异常进行捕获、处理,而异常肯定还是处理的,不然系统岂不是动不动就崩溃了,所以必须得有其他地方捕获并处理这些异常。统一异常处理应运而生,优雅的处理各种异常。本文主要介绍的是用切面方式进行统一异常处理。
目录结构
接下来逐一介绍作用
annotation包
这个包写一个注解的接口,定义全局异常注解,就是最后打在需要异常处理的方法上的注解
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface GlobalExceptionLog { Class<? extends Throwable>[] value() default {}; }
aspect包
定义处理上述注解的切面
@Component @Aspect public class GlobalExceptionAspect { @Resource private GlobalExceptionHandler globalExceptionHandler;//全局异常处理 //定义执行这个切面的注解 @Pointcut("@annotation(com.bosssoft.bes.base.common.exception.logging.annotation.GlobalExceptionLog)") public void myExceptionHandler() { } //当抛出异常后执行的方法 @AfterThrowing(throwing = "ex",pointcut = "myExceptionHandler()") public void afterThrowing(JoinPoint joinPoint,BaseException ex){ ... //全局异常处理 } }
enums包
定义枚举类,用于自定义异常
public enum ResultEnum { SUCCESS(000000,"成功"), SYSTEM_ERROR(100000,"系统错误"), ; private int code; private String message; private ResultEnum(int code, String message){ this.code = code; this.message = message; } public int getCode() { return code; } public String getMsg() { return message; } }
exception包
自定义异常类
public class BusinessException extends BaseException { public BusinessException(ResultEnum resultEnum) { super(resultEnum); } public BusinessException(String message, int code) { super(message, code); } }
handler包
全局异常处理
@ControllerAdvice//控制层增强 public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) @ResponseBody public CommonResponse handle(Exception e){ //执行方法,CommonResponse是自定义的应答类型,用其他也可以 ... }