My controller looks like the following:
@RequestMapping(value = "/cars/{types}", method = RequestMethod.PUT,
headers = "Accept=application/json")
@ResponseStatus(HttpStatus.OK)
public void startEngine(
@PathVariable @Min(0) String types, @RequestBody @Valid someObject request, BindingResult result)
throws MethodArgumentNotValidException {
if(result.hasErrors())
{
System.out.println("Error");
//Should I be throwing MethodArgumentNotValidException here? And if so how? I don't know how to retrieve the first parameter for it's constructor (MethodParameter object)
}
//Controller code
}
So after I verify whether or not my result object encountered any errors during validation, how can I then throw the MethodArgumentNotValidException? Or should Spring be already throwing that exception during validation?
MethodArgumentNotValidException. Exception to be thrown when a method argument fails validation perhaps as a result of @Valid style validation, or perhaps because it is required.
The method throws an IllegalArgumentException , as the input value is empty.
public class MethodArgumentNotValidException extends BindException. Exception to be thrown when validation on an argument annotated with @Valid fails.
public class BindException extends Exception implements BindingResult. Thrown when binding errors are considered fatal. Implements the BindingResult interface (and its super-interface Errors ) to allow for the direct analysis of binding errors. As of Spring 2.0, this is a special-purpose class.
If I remember correctly, Spring should throw MethodArgumentNotValidException
only if you have not provided an Errors
(here, BindingResult
) parameter for the @Valid
annotated parameter.
You can throw it yourself if you would like to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With