【问题标题】:How to validate path variable type: error 400 with wrong parameter and no logs in server, no error message如何验证路径变量类型:错误 400 参数错误,服务器没有日志,没有错误消息
【发布时间】:2021-03-02 12:16:19
【问题描述】:

我有一个端点:

@GetMapping("/v2/tw/{id}")
public TwDto getTw(Authentication auth, @PathVariable Long id) {
}

当我想用错误的参数类型/v2/tw/variableNoNumber 使用 Postman 获取数据时,我想在服务中有一些日志,我想得到一些验证错误。该怎么做?

我应该添加例如。 @NumberFormat?它不起作用。

我使用@ControllerAdvice,我的项目已经很老了,一切都得到了正确的验证,但这种情况对我来说很奇怪......

【问题讨论】:

  • 也许您应该将id 参数作为一个对象,然后在您的代码检查验证中。
  • @navand hmmm 也许这就是解决方案!然后我可以抛出任何将在 ControllerAdvice 中捕获的 Excption
  • 但是我不记得如果我使用 Object 参数类型而不是 Long/Integer...也许有更好的解决方案?
  • 时间已经过去了,也许最近发生了一些变化,但是 AFAIK 你无法验证类型。 stackoverflow.com/questions/44072595/…
  • 这能回答你的问题吗? How to validate Spring MVC @PathVariable values?

标签: java spring-boot


【解决方案1】:

您可以编写自定义异常处理程序。

  • 这是您的自定义实体。

public class ApiException {
    private final String message;
    private final HttpStatus httpStatus;
 

    public ApiException(String message, HttpStatus httpStatus ) {
        this.message = message;
        this.httpStatus = httpStatus;
        this.timestamp = timestamp;
    }

    public String getMessage() {
        return message;
    }


    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    
}
  • 这是您的异常类。

public class ApiRequestException extends RuntimeException {

    public ApiRequestException(String message) {
        super(message);
    }

    public ApiRequestException(String message, Throwable cause) {
        super(message, cause);
    }

}
  • 最后是 ApiExceptionHandler
@ControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(value = {ApiRequestException.class})
    public ResponseEntity<Object> handleApiRequestException(ApiRequestException e) {
        HttpStatus badRequest = HttpStatus.BAD_REQUEST;
        ApiException apiException = new ApiException(e.getMessage(), badRequest));
        return new ResponseEntity<>(apiException, badRequest);
    }
}

例如,如果你想验证 ID,你可以写如下。

throw new ApiRequestException("Case by id" + TwDto.getId+ " was not found!");

【讨论】:

    【解决方案2】:

    我想我找到了解决问题的方法 - 而不是用一些消息抛出 400 可能就足够了:

    @GetMapping("/v2/tw/{id:\d+}")
    public TwDto getTw(Authentication auth, @PathVariable Long id) {
    }
    

    然后我得到404 error Not found,我认为这种方法比在没有任何消息的情况下返回 400 错误要好......你怎么看?

    【讨论】:

      【解决方案3】:

      您可以对参数使用注解@Valid,并使用ConstraintViolationException 处理异常。有关更多信息和详细信息,请参见此处: https://medium.com/@aamine/customized-input-validation-in-spring-boot-1927aa440bc6

      【讨论】:

      • 恐怕我有 PathVariable,而不是 RequestParam... Valid 不起作用,我仍然只收到 400 错误,没有任何日志,没有任何消息
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      相关资源
      最近更新 更多