我正在努力在我的spring boot REST api中调用被覆盖的MethodArgumentNotValidException。我的其他异常处理程序工作起来很棒,但是覆盖标准的handleMethodArgumentNotValid永远不会被触发?
有人知道我错过了什么吗?
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 {异常处理程序,通过@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);
}发布于 2019-03-20 00:50:34
显然,这是由于Spring的一些“魔法”造成的。这涉及到我不太熟悉的各种概念,因为框架“隐藏”了这种复杂性。
在我的示例中,我有一个'GET‘请求,对于这个请求,我将pathParams/requestParams映射到一个复杂的对象。作为额外的补充,我想对这些参数进行验证。
然而,由于Spring中“数据绑定到复杂对象”的工作方式,因此不需要注释。因此,这是“数据绑定”而不是“方法映射”。此特定情况触发的结果异常不是MethodArgumentNotValid,而是BindException。
Spring如何准确地将数据映射到REST调用中的对象取决于各种因素,如ContentType、使用的注释等。
发布于 2020-01-13 14:53:46
我认为您需要使用@ControllerAdvice添加@Order(Ordered.HIGHEST_PRECEDENCE)注释
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
public class FundsConfirmationExceptionHandler extends ResponseEntityExceptionHandlerhttps://stackoverflow.com/questions/55244238
复制相似问题