I\'m having trouble when Using @ControllerAdvice and @Valid annotations together in a REST controller.
I have a rest controller dec
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
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);
}
}
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.