我目前正在开发一个Spring RESTful服务,并使用验证注释来确保请求体的对象中的参数存在。但是,由于某些原因,默认情况下,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至少能够在错误消息中提供异常,让我通过最小可行产品迭代,这样虽然它可能很迟钝,但客户端最终仍然可以理解他们做错了什么,我可以稍后添加自定义错误处理,但情况似乎并非如此?
如果不是,为了正确处理验证器错误,我需要在错误/异常处理程序类中实现哪些方法?
谢谢
发布于 2020-07-23 23:11:42
您可以在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
https://stackoverflow.com/questions/63057316
复制相似问题