oberlies
oberlies

Reputation: 11723

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

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:

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

Upvotes: 7

Views: 9619

Answers (2)

diego panqueva
diego panqueva

Reputation: 51

The following solution worked for me. MissingRequestHeaderException.class this class defined my exception.

@ExceptionHandler({BadRequestException.class, ConstraintViolationException.class, MissingRequestHeaderException.class})
public ResponseEntity<Object> batRequestException(Exception e) {
    log.info(e.getMessage());
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseDTO<>(null, EResponseType.BAD_REQUEST, e.getMessage(), "400"));
}

Upvotes: 2

oberlies
oberlies

Reputation: 11723

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.

Upvotes: 6

Related Questions