定义自定义唯一索引捕获注解
/**
* @author huaqiang
* @version 1.0
* @description 自定义唯一索引异常
* @date 2023/7/28
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDuplicateKeyException {
String[] keyValuePairs();
}
定义aop切面监听注解
import com.xxx.framework.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @author huaqiang
* @version 1.0
* @description 唯一索引异常捕获
* @date 2023/7/28
*/
@Aspect
@Component
@Slf4j
public class CustomDuplicateKeyExceptionAspect {
// 定义切点
@Pointcut("@annotation(com.nos.express.common.aspect.CustomDuplicateKeyException)")
public void doAspect() {
}
@Around("doAspect() && @annotation(customDuplicateKeyException)")
public Object doAround(ProceedingJoinPoint joinPoint, CustomDuplicateKeyException customDuplicateKeyException) throws Throwable {
Object proceed = new Object();
// 值是被拦截方法的返回值
try {
proceed = joinPoint.proceed();
} catch (DuplicateKeyException e) {
HashMap<String, String> uniqMap = new HashMap<>();
String[] keyValuePairs = customDuplicateKeyException.keyValuePairs();
for (String keyValuePair : keyValuePairs) {
String[] values = keyValuePair.split("=");
String uniqName = values[0];
String message = values[1];
uniqMap.put(uniqName,message);
}
uniqExceptionDealWith(e, uniqMap);
}
return proceed;
}
/**
* 唯一索引异常抛出
* @param e
* @param uniqMap
*/
private static void uniqExceptionDealWith(DuplicateKeyException e, Map<String, String> uniqMap) {
if (Objects.equals(null, uniqMap)) {
throw new RuntimeException("uniqExceptionDealWith(),传入map为空null!");
}
for (String key : uniqMap.keySet()) {
if (Objects.requireNonNull(e.getMessage()).contains(key)) {
throw new BusinessException(uniqMap.get(key));
}
}
}
}
在方法上打注解的形式进行监听
@CustomDuplicateKeyException(keyValuePairs = {"uniq_xxx1=xxx已存在!"})
@Override
public Boolean add(xxxDto dto) {
xxxEntity entity = new xxxxEntity();
BeanUtils.copyProperties(dto, entity);
return this.save(entity);
}