有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring验证程序未向客户端提供消息

我目前正在开发一个SpringRESTful服务,并使用验证注释来确保请求主体对象中的参数存在。但是,由于某些原因,Spring验证在默认情况下似乎没有向客户机用户提供有关其请求可能无效的原因的任何信息

数据对象类:

....
    @Min(10000000000L)
    @Max(19999999999L)
    private long id;
    
    private boolean restricted;
.....

控制器:

@PostMapping("/userRestriction")
    public ResponseEntity<String> userRestriction(
            @Valid @RequestBody(required = true) User user) {

职位:

{
    "id":"A",
    "restricted":false
}

结果:

{
    "timestamp": "2020-07-23T14:20:57.273+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/userRestriction"
}

日志:

2020-07-23 09:20:57.271  WARN 28035 --- [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `long` from String "A": not a valid Long value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `long` from String "A": not a valid Long value
 at [Source: (PushbackInputStream); line: 2, column: 11] (through reference chain: myPackage.dataObjects.User["id"])]

我希望Spring至少能够在错误消息中提供异常,让我通过一个最小可行的产品迭代,这样,虽然它可能是迟钝的,但客户仍然可以最终理解他们做错了什么,我可以在以后添加自定义错误处理,但情况似乎不是这样

如果不是,我需要在错误/异常处理程序类中实现哪些方法来正确处理验证器错误

谢谢


共 (1) 个答案

  1. # 1 楼答案

    您可以在userRestriction()的参数中添加以下类BindingResult bindingResult

    @PostMapping("/userRestriction")
    public ResponseEntity<String> userRestriction(
            @Valid @RequestBody(required = true) User user, BindingResult bindingResult)
    

    然后在你的方法中,你可以做如下事情

    if (bindingResult.hasErrors()) {
        //Whatever you want to do
    }
    

    BindingResult提供对与@Valid相关联的Bean的验证的访问和处理

    有关如何处理它的更多信息,请参见此处:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/BindingResult.html

    我建议您使用方法getAllErrors(),它将返回验证给出的所有错误的列表。 您还可以实现在存在这些错误时引发的自定义异常

    让我给您一个代码片段,用于使用Spring实现处理程序异常

    @ControllerAdvice
    public class RestResponseEntityExceptionHandler 
     extends ResponseEntityExceptionHandler {
    
    @ExceptionHandler(value 
      = { IllegalArgumentException.class, IllegalStateException.class })
    protected ResponseEntity<Object> handleConflict(
      RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
    }
    

    这是迄今为止我使用过的最有用的,您只需要根据自己的需要调整它。您可以在本教程之后找到更多信息:https://www.baeldung.com/exception-handling-for-rest-with-spring