简体   繁体   English

如何在 SpringBoot REST Api 中调用重写的 handleMethodArgumentNotValid?

[英]How to invoke an overridden handleMethodArgumentNotValid in a SpringBoot REST Api?

I am struggling to invoke the overridden MethodArgumentNotValidException in my spring boot REST api.我正在努力在我的 Spring Boot REST api 中调用被覆盖的 MethodArgumentNotValidException。 My other exception handlers work like a charm, however overriding the standard handleMethodArgumentNotValid is never getting triggered?我的其他异常处理程序就像一个魅力,但是覆盖标准 handleMethodArgumentNotValid 永远不会被触发?

Anyone got a clue what I missed?有人知道我错过了什么吗?

Pojo波乔

public class FundsConfirmationRequest {
  @NotNull(message = "Required Parameter: Account Identifier.")
  private String accountId;
  @NotNull(message = "Required Parameter: Transaction Amount.")
  @Digits(integer=12, fraction=5, message = "Fractions limited to 5 digits.")
  private BigDecimal amount;
  @NotNull(message = "Required Paramater: Currency Code.")
  @Size(min = 3, max = 3, message = "Use ISO4217 Currency Code standard.")
  private String ccy;
  private String cardNumber;
  private String payee;

   public FundsConfirmationRequest() { } 
}

Controller-Method:控制器方法:

@RestController("fundsConfirmationController")
@RequestMapping(
        value="/accounts/{accountId}/funds-confirmations"
)
public class FundsConfirmationController implements FundsConfirmationControllerI {

    @GetMapping(
            headers = {"X-CAF-MSGID", "X-AccessToken"},
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE
    )
    public ResponseEntity<?> fundsConfirmation(@RequestHeader(value="X-CAF-MSGID") String messageId,
                                               @RequestHeader(value="X-AccessToken") String accessToken,
                                               @Valid FundsConfirmationRequest requestParams) throws FIClientException, FIParseException {

Exception handler via @RestControllerAdvice通过@RestControllerAdvice 的异常处理程序

@RestControllerAdvice
public class FundsConfirmationExceptionHandler extends ResponseEntityExceptionHandler {

    //Existing Exception Handlers
    @Override
    public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        System.out.println("Custom handleMethodArgumentNotValid method");
        FundsConfirmationError responseBody = new FundsConfirmationError(HttpStatus.BAD_REQUEST.toString(), "Input Validation Failed. Parameter.: " + ex.getParameter().getParameterName() + " Value.: " + ex.getParameter().getParameter().toString() + " " + ex.getMessage(), Severity.ERROR.toString(), Sources.LOCAL_CAF_API.toString() );
        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .header("X-CAF-ResponseID", request.getHeader("X-CAF-MSGID"))
                .body(responseBody);
    }

Apparently this is happening due to some Spring 'magic'.显然,这是由于一些 Spring 的“魔法”而发生的。 This is touching various concepts I was not very familiar with because the framework 'hides' this complexity away.这涉及到我不太熟悉的各种概念,因为框架“隐藏”了这种复杂性。

In my example I have a 'GET' request for which I map the pathParams/requestParams to a complex object.在我的示例中,我有一个“GET”请求,我将 pathParams/requestParams 映射到一个复杂对象。 As an extra I want to do validation on these Params.另外,我想对这些参数进行验证。

However due to how 'data binding to complex objects' works in Spring there is no annotation required.然而,由于“数据绑定到复杂对象”在 Spring 中的工作方式,不需要注释。 As a result this is 'Data Binding' and not 'Method Mapping'.因此,这是“数据绑定”而不是“方法映射”。 The resulting exception being triggered by this specific case is not MethodArgumentNotValid but it is a BindException.此特定情况触发的结果异常不是 MethodArgumentNotValid 而是 BindException。

How exactly Spring maps data to objects in a REST call is dependent on various things like ContentType, Annotations Used, ... Spring 如何在 REST 调用中准确地将数据映射到对象取决于各种事物,例如 ContentType、Annotations Used,...

I think you need to add @Order(Ordered.HIGHEST_PRECEDENCE) annotation with @ControllerAdvice我认为您需要使用@ControllerAdvice添加@Order(Ordered.HIGHEST_PRECEDENCE)注释

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM