如何拦截@Repository层方法抛出的DataAccessException并获取对应错误码
解决方案
使用Spring AOP切入所有Repository层方法,捕获DataAccessException后解析对应方法的@ErrorCode注解,再抛出带错误码的自定义异常即可实现需求,具体步骤如下:
步骤1:定义基础结构(已实现可跳过)
首先确认自定义注解和自定义业务异常存在:
// 自定义ErrorCode注解 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ErrorCode { String value(); } // 自定义业务异常,携带错误码 public class RepositoryBusinessException extends RuntimeException { private final String errorCode; public RepositoryBusinessException(String errorCode, String message, Throwable cause) { super(message, cause); this.errorCode = errorCode; } public String getErrorCode() { return errorCode; } }
步骤2:实现AOP切面
编写切面类切入所有Repository方法,处理异常逻辑:
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Component; import java.lang.reflect.Method; @Aspect @Component public class RepositoryExceptionHandlerAspect { /** * 切点配置:切所有Spring Data Repository接口的公共方法 * 如需缩小范围可改为指定项目Repository包路径,例如: * @Around("execution(public * com.xxx.yourproject.repository.*.*(..))") */ @Around("execution(public * org.springframework.data.repository.Repository+.*(..))") public Object handleRepositoryException(ProceedingJoinPoint joinPoint) throws Throwable { try { return joinPoint.proceed(); } catch (DataAccessException e) { // 获取触发异常的方法对象 Method targetMethod = ((MethodSignature) joinPoint.getSignature()).getMethod(); // 读取方法上的ErrorCode注解 ErrorCode codeAnnotation = targetMethod.getAnnotation(ErrorCode.class); // 无注解时使用默认错误码 String errorCode = codeAnnotation != null ? codeAnnotation.value() : "E0000"; // 抛出携带错误码的自定义异常 throw new RepositoryBusinessException(errorCode, "数据操作失败", e); } } }
步骤3:开启AOP配置
如果项目未默认开启AOP自动代理,需要在启动类或者配置类上添加@EnableAspectJAutoProxy注解。
效果验证
后续调用Repository方法触发数据访问异常时,会自动抛出携带对应@ErrorCode的自定义异常,你可以通过全局异常处理器@RestControllerAdvice捕获该异常,直接将错误码返回给前端即可。
内容的提问来源于stack exchange,提问作者Eng.Fouad
相关产品推荐
相关产品推荐

