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

how can I custom error message in AOP around annotations?

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

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

但我无法进入正题:(

交易方面class

    @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;
    }

错误信息class

@Getter
@Setter
public class ErrorMessage {

    private int errorCode;
    private String errorMessage;

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

GroupExceptionAdvice class

@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 class 没有扩展任何 ExceptionThrowable,所以你怎么能扔掉它?该代码甚至不应该编译并产生如下编译错误:

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

即在你的样本中 class 我你应该写类似

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

检查异常或

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

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