gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:47:28 24 4
gpt4 key购买 nike

我正在努力在 Spring Boot REST api 中调用重写的 MethodArgumentNotValidException 。我的其他异常处理程序工作起来就像一个魅力,但是覆盖标准的handleMethodArgumentNotValid永远不会被触发?

有人知道我错过了什么吗?

波乔

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 方法:

@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 {

通过@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);
}

最佳答案

显然,这是由于 Spring 的一些“魔法”而发生的。这涉及到我不太熟悉的各种概念,因为框架“隐藏”了这种复杂性。

在我的示例中,我有一个“GET”请求,我将其 pathParams/requestParams 映射到一个复杂对象。另外,我想对这些参数进行验证。

但是,由于 Spring 中“数据绑定(bind)到复杂对象”的工作方式,因此不需要注释。因此,这是“数据绑定(bind)”而不是“方法映射”。此特定情况触发的结果异常不是 MethodArgumentNotValid,而是 BindException。

Spring 如何准确地将数据映射到 REST 调用中的对象取决于各种因素,例如 ContentType、使用的注释......

关于java - 如何在 SpringBoot REST Api 中调用重写的handleMethodArgumentNotValid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55244238/

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