Have Spring respond with 400 (instead of 500) in case of a request header validation error

北城以北 提交于 2019-12-11 05:26:22

问题


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:

  • For invalid @RequestBody parameters, Spring responds with 400
  • For invalid @RequestHeader, @PathVariable, and @RequestParam parameters, Spring responds with 500.

Can this be changed so that Spring responds with the same 400 response in all cases?


This is my code:

@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;
    }
}

回答1:


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);
    }

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.



来源:https://stackoverflow.com/questions/54905691/have-spring-respond-with-400-instead-of-500-in-case-of-a-request-header-valida

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!