gpt4 book ai didi

java - 如何在 AOP 中围绕注释自定义错误消息?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:43:44 24 4
gpt4 key购买 nike

我想在 AOP 中围绕注释自定义错误消息。我以前使用过@RestControllerAdvice,但它在 AOP around 方法中不起作用。它输出默认错误消息。

我尝试在 try ~ catch 中输入消息,我知道这很奇怪,例如////1 或////2

但我无法进入正题:(

TransactionAspect 类

    @Around("execution(* com.bono.server.controller..*(..))")
@Transactional
public Object caculatePerformanceTime(ProceedingJoinPoint proceedingJoinPoint) {
Object result = null;
try {
result = proceedingJoinPoint.proceed();
} catch (CustomeException e) { ////// 1
throw new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
catch (Throwable throwable) { /////// 2
return new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
return result;
}

ErrorMessage 类

@Getter
@Setter
public class ErrorMessage {

private int errorCode;
private String errorMessage;

public ErrorMessage(CustomError customError) {
this.errorCode = customError.errorCode();
this.errorMessage = customError.errorMessage();
}
}

GroupExceptionAdvice 类

@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GroupExceptionAdvice extends ResponseEntityExceptionHandler {

//// 1
@ExceptionHandler(value = CustomeException.class)
public ResponseEntity<CustomErrorResponse> customhandleNotSatisfied(Exception ex, WebRequest request) {
CustomErrorResponse error = new CustomErrorResponse();
error.setTimestamp(LocalDateTime.now());
error.setError(ex.getMessage());
error.setStatus(HttpStatus.NOT_FOUND.value());

return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}

//// 2
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = CustomException.class)
public ErrorMessage handlerUnResolvedAddressException(MisTypingException e) {
return new ErrorMessage(CustomError.HTTP_400_MISTYPE);
}
}
{
"timestamp": "2019-08-12T01:14:16.467+0000",
"status": 500,
"error": "Internal Server Error",
"message": "class com.bono.server.config.exception.ErrorMessage cannot be cast to class org.springframework.http.ResponseEntity (com.bono.server.config.exception.ErrorMessage and org.springframework.http.ResponseEntity are in unnamed module of loader 'app')",
"path": "/bono/api/alarm"
}

我想这样显示

{
"code" : 102,
"message" : "got it !"
}

最佳答案

将我之前的评论转化为答案,因为 OP 说他们解决了他的问题。

您的ErrorMessage 类没有扩展任何ExceptionThrowable,那么您如何抛出它呢?该代码甚至不应该编译并产生如下编译错误:

No exception of type ErrorMessage can be thrown;
an exception type must be a subclass of Throwable

即在你的示例课中,你应该写类似

public class ErrorMessage extends Exception {
// (...)
}

检查异常或

public class ErrorMessage extends RuntimeException {
// (...)
}

对于非检查异常。但是您的类定义没有扩展任何内容,即它隐式地直接扩展了 Object

关于java - 如何在 AOP 中围绕注释自定义错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57454841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com