Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MethodArgumentNotValidException not thrown

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?

like image 557
user1553248 Avatar asked May 14 '14 00:05

user1553248


People also ask

When MethodArgumentNotValidException is thrown?

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.

What Exception does @notblank throw?

The method throws an IllegalArgumentException , as the input value is empty.

What is MethodArgumentNotValidException?

public class MethodArgumentNotValidException extends BindException. Exception to be thrown when validation on an argument annotated with @Valid fails.

What is BindException in spring?

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.


1 Answers

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.

like image 67
Sotirios Delimanolis Avatar answered Oct 13 '22 03:10

Sotirios Delimanolis