小编典典

如何在Spring Boot应用程序中使用Hibernate Validation进行Bean验证?

java

我正在Spring
Boot应用程序中学习有关休眠验证的信息,我有一个Rest控制器和一个POST方法。当我发出请求时,如果未成功验证字段,则客户端应收到400错误请求,并且在正文中会显示类似“验证失败”的消息。我尝试这样做,但是没有收到消息。

这是身体:

{
    "timestamp": "2020-06-06T07:56:11.377+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/ibantowallet"
}

在控制台日志中,我得到:

2020-06-06 10:56:11.371  WARN 7552 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity com.dgs.demotrans.api.TransactionController.sendMoneyIbanToWallet(com.dgs.demotrans.request.IbanToWalletRequest): [Field error in object 'ibanToWalletRequest' on field 'fromIban': rejected value [FR9151000 0000 0123 4567 89]; codes [Pattern.ibanToWalletRequest.fromIban,Pattern.fromIban,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [ibanToWalletRequest.fromIban,fromIban]; arguments []; default message [fromIban],[Ljavax.validation.constraints.Pattern$Flag;@3c555785,[a-zA-Z]{2}\d{2}[ ]\d{4}[ ]\d{4}[ ]\d{4}[ ]\d{4}[ ]\d{2}|DE\d{20}]; default message [IBAN validation failed]] ]

因此,该消息为空,我希望客户端收到特定消息“ IBAN验证失败”或“请提供金额”,等等。我该怎么做?先感谢您!


阅读 199

收藏
2020-11-30

共1个答案

小编典典

您要么必须创建一个ControllerAdvice处理MethodArgumentNotValidExceptionhibernate验证程序抛出的错误的方法,例如以下示例:

    @ResponseStatus(BAD_REQUEST)
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CustomError methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        List<org.springframework.validation.FieldError> fieldErrors = result.getFieldErrors();
        return mapToCustomError(fieldErrors);
    }

或者,您可以注入BindingResult控制器方法并检查其中的验证是否失败:

    @PostMapping("/ibantoiban")
    public ResponseEntity<String> sendMoneyIbanToIban(@Valid @RequestBody IbanToIbanRequest ibanToIbanRequest, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) { /** handle error here */ }
        Transaction transaction = transactionService.sendMoneyIbanToIban(ibanToIbanRequest);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Location", "/ibantoiban" + transaction.getTransactionId().toString());
        return new ResponseEntity(headers, HttpStatus.CREATED);
    }
2020-11-30