22

I'm having trouble when Using @ControllerAdvice and @Valid annotations together in a REST controller.

I have a rest controller declared as follows:

@Controller
public class RestExample {

    ...

    /**
     * <XmlRequestUser><username>user1</username><password>password</password><name>Name</name><surname>Surname</surname></XmlRequestUser>
     * curl -d "@restAddRequest.xml" -H "Content-Type:text/xml" http://localhost:8080/SpringExamples/servlets/rest/add
     */
    @RequestMapping(value="rest/add", method=RequestMethod.POST)
    public @ResponseBody String add(@Valid @RequestBody XmlRequestUser xmlUser) {
        User user = new User();
        user.setUsername(xmlUser.getUsername());
        user.setPassword(xmlUser.getPassword());
        user.setName(xmlUser.getName());
        user.setSurname(xmlUser.getSurname());

        // add user to the database
        StaticData.users.put(xmlUser.getUsername(), user);
        LOG.info("added user " + xmlUser.getUsername());

        return "added user " + user.getUsername();
    }
}

And an ErrorHandler class:

@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {

    private static Logger LOG = Logger.getLogger(RestErrorHandler.class);


    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Object> handleException(final RuntimeException e, WebRequest request) {
        LOG.error(e);

        String bodyOfResponse = e.getMessage();
        return handleExceptionInternal(e, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}

The problem is that, if I add a "throw new RuntimeException" within the method RestExample.add then the exception is correctly handled by RestErrorHandler class.

However when curling a not valid request to the controller the RestErrorHandler doesn't catch the exception thrown by the validator and I receive a 400 BadRequest response. (For not valid request I mean an xml request where Username is not specified)

Note that XmlRequestUser class is autogenerated by the plugin maven-jaxb2-plugin + krasa-jaxb-tools (pom.xml):

<plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <schemaDirectory>src/main/xsd</schemaDirectory>
        <schemaIncludes>
            <include>*.xsd</include>
        </schemaIncludes>
        <args>
            <arg>-XJsr303Annotations</arg>
            <arg>-XJsr303Annotations:targetNamespace=http://www.foo.com/bar</arg>
        </args>
        <plugins>
            <plugin>
                <groupId>com.github.krasa</groupId>
                <artifactId>krasa-jaxb-tools</artifactId>
                <version>${krasa-jaxb-tools.version}</version>
            </plugin>
        </plugins>
    </configuration>
</plugin>

The generated class has correctly a @NotNull Annotation on Username and Password fields.

My context.xml is very easy, containing just a scanner for controllers and enabling mvc:annotation-driven

<context:component-scan base-package="com.aa.rest" />
<mvc:annotation-driven />

Does anybody know how to make working @ControllerAdvice and @Valid annotations together in a REST controller?

Thanks in advance. Antonio

daemon_nio
  • 1,446
  • 1
  • 16
  • 19

3 Answers3

40

You are on the right track, but you need to override the handleMethodArgumentNotValid() instead of the handleException() method, e.g.

@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException exception,
            HttpHeaders headers,
            HttpStatus status,
            WebRequest request) {

        LOG.error(exception);
        String bodyOfResponse = exception.getMessage();
        return new ResponseEntity(errorMessage, headers, status);
    }
}

From the JavaDoc of MethodArgumentNotValidException:

Exception to be thrown when validation on an argument annotated with @Valid fails.

In other words, a MethodArgumentNotValidException is thrown when the validation fails. It is handled by the handleMethodArgumentNotValid() method provided by the ResponseEntityExceptionHandler, that needs to be overridden if you would like a custom implementation.

bdkosher
  • 5,753
  • 2
  • 33
  • 40
matsev
  • 32,104
  • 16
  • 121
  • 156
  • 1
    @matsev Instead of extending ResponseEntityExceptionHandler and overriding the handleMethodArgumentNotValid method, couldn't he simply use a @ExceptionHandler(MethodArgumentNotValidException.class) ? – Stephane May 11 '14 at 17:12
  • @StephaneEybert Sure, why not. I chose to extend the `ResponseEntityExceptionHandler` because it was already extended in the original question. Related: by using the `@ControllerAdvice` annotation (regardless if you extend the `ResponseEntityExceptionHandler` or use the `@ExceptionHandler` annotation) you get consistent error handling for all controllers. – matsev May 12 '14 at 14:24
  • I have overriden method handleMethodArgumentNotValid, but that seems to be unused, I checked with debugging by setting breakpoint. Is there any other configuration I need to do beside just overriding the method? – Shafiul Jan 05 '17 at 10:08
  • 2
    i override handleMethodArgumentNotValid() in @controllerAdvice but i am not able to handle exception when required parameter not present – Bharti Ladumor Sep 26 '18 at 09:15
  • same here have you found a solution @BhartiLadumor? and @shafiul – Aliy Jul 23 '19 at 11:04
  • I solved the issue with required parameters not present mentioned by @BhartiLadumor removing `@NotNull` lombok annotations from the fields. This way the objects had chance to be instantiated and then be validated. – dbaltor May 07 '22 at 18:14
4

Better format of return message:

@ControllerAdvice
public class MyControllerAdvice extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex,
        HttpHeaders headers,
        HttpStatus status,
        WebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
            .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
            .collect(Collectors.toList());

    return handleExceptionInternal(ex, "Method argument not valid, fieldErrors:" + fieldErrors ,new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }

}
  • Thanks for this. As a slight improvement, you can collect your stream using `toMap` and pass the resulting map with the fields direclty to `handleExceptionInternal` constructor. – dbaltor May 07 '22 at 15:34
1

In addition to this I had another problem on recursive validation.

The generated classes were missing a @valid annotation on the other XmlElements.

The reason for this is related to the fact that I was wrongly using the namespaces:

The plugin is configured to use a particular namespace

<arg>-XJsr303Annotations:targetNamespace=http://www.foo.com/bar</arg>

So the XSD need to have this as target namespace (e.g.):

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.foo.com/bar"
    xmlns:foo="http://www.foo.com/bar" >

    <xs:complexType name="XmlPassword">
        <xs:sequence>
            <xs:element name="password" type="xs:string" />
            <xs:element name="encryption" type="xs:string" />
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="XmlToken">
        <xs:sequence>
            <xs:element name="password" type="foo:XmlPassword" />
        </xs:sequence>
    </xs:complexType>

</xs:schema>

Kind regards Antonio

daemon_nio
  • 1,446
  • 1
  • 16
  • 19