首页 > 解决方案 > 如何在 AOP 中围绕注释自定义错误消息?

问题描述

我想在 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;
    }

错误消息类

@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 !"
}

标签: javaspringspring-bootspring-aopcustom-errors

解决方案


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

你的ErrorMessage类没有扩展任何Exceptionor Throwable,那么你怎么能扔它呢?该代码甚至不应该编译并产生如下编译错误:

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


推荐阅读