在我的项目中,我有一个域层,它基本上是 POJO 和一个位于域层之上的 Spring 控制器/服务层。我还有一个位于服务和域之间的 AOP 层。
我的域层正在抛出业务异常,这些异常现在正在服务层中处理。
但是我想更改它,以便从领域层抛出的异常将在 AOP 层中处理。 AOP层将某种错误响应并将其发送回Spring控制器/Web服务层。
我可以创建一个 IBizResponse 并创建它的两个子类/接口(可能是 SuccessResponse 和 ErrorResponse),并使我的域层方法返回 IBizResponse。但是我无法弄清楚如何让 AOP 将 ErrorResponse 对象返回到服务层。
我遇到了同样的场景,在发生任何异常处理时,我必须返回错误响应 DTO。在 @Aspect 类中,
@Aspect
@Component
public class MyAspect{
private static final Logger LOGGER = LoggerFactory.getLogger(MyAspect.class);
@Pointcut("execution(* com.linda.dao.strategy.*.*(..))")
public void strategyMethods() { }
@Pointcut("execution(* com.linda.controller.*.*(..)) || execution(* com.linda.Manager.*(..))")
public void controllerMethods(){ }
@Around("strategyMethods()")
public Object profileStrategyMethods(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
Object output = null;
LOGGER.info("Class:"+pjp.getTarget().getClass()+" entry -> method ->"+pjp.getSignature().getName());
try{
output = pjp.proceed();
long elapsedTime = System.currentTimeMillis() - start;
LOGGER.info("Method execution time: " + elapsedTime + " milliseconds.");
LOGGER.info("Class:"+pjp.getTarget().getClass()+" exit -> method ->"+pjp.getSignature().getName());
}catch(Throwable t){
throw new InternalServerException(t.getMessage());
}
return output;
}
@AfterThrowing(pointcut="execution(* com.linda.dao.strategy.*.*(..)) || execution(* com.linda.controller.*.*(..)) || execution(* com.linda.Manager.*(..))",throwing = "ex")
public void doRecoveryActions(JoinPoint joinPoint, Throwable ex) {
Signature signature = joinPoint.getSignature();
String methodName = signature.getName();
String stuff = signature.toString();
String arguments = Arrays.toString(joinPoint.getArgs());
LOGGER.error("Write something in the log... We have caught exception in method: "
+ methodName + " with arguments "
+ arguments + "\nand the full toString: " + stuff + "\nthe exception is: "
+ ex.getMessage());
}
}
定义了另一个类来进行异常处理,如下所示:
@ControllerAdvice
public class ExceptionLogAdvice {
@ExceptionHandler(InternalServerException.class)
@ResponseStatus(HttpStatus.BAD_GATEWAY)
@ResponseBody
public ResponseEntity<Object> handleValidationException(final InternalServerException internalServerException){
ErrorResponseDTO dto = constructErrorResponse(internalServerException);
return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(dto);
}
}
对代码进行了一些调整,因为我无法共享实际的代码。希望我把这个概念说清楚了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)