如果请求标头验证错误,让Spring响应400(而不是500) [英] Have Spring respond with 400 (instead of 500) in case of a request header validation error
问题描述
在对Spring MVC @RequestMapping
方法的参数进行验证时,Spring会根据参数的类型以不同的状态代码进行响应:
When using validation for parameters of a Spring MVC @RequestMapping
method, Spring responds with with different status codes depending on the type of the parameter:
- 对于无效的
@RequestBody
参数,Spring响应为400 - 对于无效的
@RequestHeader
,@PathVariable
和@RequestParam
参数,Spring响应为500.
- For invalid
@RequestBody
parameters, Spring responds with 400 - For invalid
@RequestHeader
,@PathVariable
, and@RequestParam
parameters, Spring responds with 500.
可以更改此设置,以便在所有情况下Spring都以相同的400响应进行响应吗?
Can this be changed so that Spring responds with the same 400 response in all cases?
这是我的代码:
@Controller
@Validated
public class WebController {
@RequestMapping(method = RequestMethod.POST, path = "/action")
public ResponseEntity<String> doAction(
@RequestHeader("Header-Name") @Valid LatinString headerValue,
@RequestBody @Valid Struct body) {
return new ResponseEntity<>(HttpStatus.OK);
}
}
public class LatinString {
@Pattern(regexp = "[A-Za-z]*")
private String value;
public LatinString(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class Struct {
@Pattern(regexp = "[A-Za-z0-9.-]{1,255}")
private String domain;
public String getDomain() {
return domain;
}
}
推荐答案
我认为可以通过处理异常类型ConstraintViolationException
来获取正确的状态代码(400).为此,需要将以下代码添加到@Controller
或@ControllerAdvice
:
I figured that one can get the right status code (400) by handling the exception type ConstraintViolationException
. To do this, one needs to add the following code to the @Controller
or a @ControllerAdvice
:
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<String> onValidationError(Exception ex) {
return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
}
不幸的是,它没有像错误的@RequestBody
请求那样包含不错的错误消息正文,所以我想知道是否有更好的解决方案.
Unfortunately, this doesn't include the nice error message body like for requests with invalid @RequestBody
, so I wonder if there is a better solution.
这篇关于如果请求标头验证错误,让Spring响应400(而不是500)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!