spring-framework: Improve the experience of handling validation errors in controller methods

Affects: 5.3.1 Relates to #23107

Basically, I have the exact same feeling as the author did but he never clarified his point.

You can validate a DTO using @Valid annotation (whether it is built from a bunch of query parameters or from the body) but you can’t validate literals like that. So, to validate a request parameter or a path parameter, one has to apply @Validated annotation on the controller class level to enable the AOP proxy for method validation, then it will pick up any JSR 380 annotations.

So, here is a little example. Given the following definition:

class UserDto { @Email String email; }

@RestController
@RequestMapping("users")
@Validated
class UserController {
  
  @PostMapping
  void createUser(@Valid @RequestBody UserDto userDto) {...}
  
  @GetMapping("{email}")
  UserDto getUser(@Email @PathVariable String email) {...}

If we send the following requests, we will get these results:

--------->
POST users
{
  "email": "invalid-email"
}

<---------
throws MethodArgumentNotValidException

--------->
GET users/invalid-email
<---------
throws ConstraintViolationException

Now, handling these 2 is not very nice although we want the same result in the end:

class ValidationErrorResponse { List<Violation> violations; }
class Violation { String fieldName, message; }

  @ExceptionHandler
  ResponseEntity<ValidationErrorResponse> onConstraintValidationException(ConstraintViolationException e) {
    ValidationErrorResponse error = new ValidationErrorResponse();
    for (ConstraintViolation violation : e.getConstraintViolations()) {
      error.getViolations().add(
        new Violation(violation.getPropertyPath().toString(), violation.getMessage()));
    }
    return ResponseEntity.badRequest().body(error);
  }

  @ExceptionHandler
  ResponseEntity<ValidationErrorResponse> onMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    ValidationErrorResponse error = new ValidationErrorResponse();
    for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
      error.getViolations().add(
        new Violation(fieldError.getField(), fieldError.getDefaultMessage()));
    }
    return ResponseEntity.badRequest().body(error);
  }

So, I see 3 inconveniences:

  • I have to always specify @Valid annotation whenever I have a @RequestBody. Can’t we just assume I want to validate all bodies? I feel like I might forget it in one place and it won’t be validated. Or maybe we could add @Valid onto the DTO class itself and look there for it? Or maybe we could just scan all fields and see if any field has the @Constraint annotation on it?
  • I have to always specify @Validated annotation on the controller class level to inspect the literals. Why doesn’t it inspect them by default since it already searches for @Valid/@Validated on the body?
  • Error handling is cumbersome

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 10
  • Comments: 15 (14 by maintainers)

Commits related to this issue

Most upvoted comments

@ascopes thanks for the ideas to group errors by method parameter (headers, path variables, etc). That’s easier now with #29825 where MethodValidationException exposes ParameterValidationResults, and each has a MethodParameter that in turn provides access to annotations. This is method validation support from spring-context, but the goal is to improve further at the web level with #30644 for M2 so you can subscribe there for progress and feedback.

As for https://github.com/spring-projects/spring-framework/issues/26219#issuecomment-1195260724, I see your point there although for error handling purposes you still need to differentiate which is request header, path variable, etc. In addition, the method validation support we are now adding should be able to address these needs for error handling.

Is there any update on this issue, or any plans that relate to this issue?

Thanks for all feedback @Sam-Kruglov and everyone else who commented. I’ve created #29825 as the main issue for validation improvements targeting 6.1 M1. Please, have a look at the details in the description of that issue, and provide feedback as needed.

I’ll leave this issue open, and schedule it for 6.1 M1 too, as it has a number of extra pointers such as the ones for TypeMismatchException and MissingServletRequestParameterException, and for Jackson’s MismatchedInputException. We’ll likely create separate issues for those, but I’ll use this as a checklist to ensure we’ve addressed the feedback from all comments.

The thing I wish we could do with this is be able to generate a consistent header name, cookie name, path variable, JSON path or xpath from the property path without adding massive amounts of reflective code. This would be really helpful for giving error messages to the user that reflect the payload shape rather than the spring internal representation which may differ with some Jackson annotations like unwrapping.

{
  "status": 400,
  "title": "Bad Request",
  "detail": "Validation failed",
  "invalidParams": [
    {
      "location": "headers",
      "name": "X-Request-ID",
      "reason": "Must be a non-empty string"
    },
    {
      "location": "body",
      "name": "$.user.name",
      "reason": "Must be specified"
    }
  ]
}

While I can write tonnes of code to try and cover the cases, it would be a great set of features to have internally. Error messages that use standard notations to refer to the request format would also prevent leaking internal implementation detail.

The issue I currently see with the Spring 5.x.x branch is that since there is no consistent way to generate tidy validation without dealing with lots of edge cases, everyone seems to end up implementing their own solutions to this, so there is never a standard format that is widely accepted. Most enterprise companies won’t use the current binding error responses on their public facing systems because the error messages can leak internal system details like the platform and libraries in use, or the error messages don’t tarry up with the request format if snake_case, kebab-case, or custom named attributes are used.

Businesses then consider that to be a security risk in some cases. (Security through obscurity isn’t really an excuse in my opinion but opinions on the subject tend to differ wildly between people).

One thing that does come to mind to make this easier is how JAXRS allows @BeanParam to define beans containing common request attributes. That would not only allow reduction of parameters crammed with lots of annotations, but would also allow using a single validator to cover the headers, path, and body rather than needing lots of separate components to do this.

It would also allow body validation failures to be reported alongside header validation errors.

@Validated
public record NewUserRequest(
  @NotBlank @RequestHeader("X-Request-ID") String requestId,
  @NotNull @Valid @RequestBody NewUser body
) { }

...

@PostMapping("/users")
public void newUser(@Valid @RequestBean NewUserRequest request) {
    ...
}

From previous experience, BeanParam in JAXRS made consistent validation much simpler to handle.

This would also potentially make using bean validation with functional routing easier too, as you could still produce an annotated payload and validate it. It isn’t uncommon to want to move a lot of headers, path variables, the body, and other components around as one bean between components either.

@ascopes thanks for your input!

I kind of agree that ConstraintViolationException should be a server error. The reason is that you can annotate any @Component with @Validated and validate method parameters. These can come from a 3rd party API for example, so it’s you who should decide for sure if it’s the client’s fault or not. Or you can just throw this exception yourself because it’s not owned by Spring. Or Hibernate could throw it before saving stuff to the database. However, I think if it’s originated from a @Controller class, it should definitely be a client error like I stated here.

About ConstraintViolationException vs MethodArgumentNotValidException I explained here. Basically constraint error originates from @Validated. I agree that it should be somehow refactored.

About property path, not sure what you mean. You can access constraintViolationException.constraintViolations[*].propertyPath to build the location in your example. As for the access to all annotations of each property along the way, I don’t see how it would be useful: if I have 10 different @Pattern annotations on a field and I only failed one, I don’t want to see all 10 errors in the response but I do want to see all 10 in the API documentation but that’s different. So, I think just having access to the name of the property is fine. Take a look at my test cases here, they use a nested field like that and the response contains the proper path. Exceptions handled are MethodArgumentNotValidException (JSR 380), and HttpMessageNotReadableException (wrong data type in JSON).

About correlation id, not sure again why would you want it inside the error response body, distributed tracing is usually done in headers, not in the body. You would still have the trace id in the response header even if that was a successful response.

I’m not sure if I missed something or not, let me know.