Spring Rest ErrorHandling @ControllerAdvice / @Valid

前端 未结 3 494
傲寒
傲寒 2020-12-30 03:29

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

I have a rest controller dec

相关标签:
3条回答
  • 2020-12-30 03:52

    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

    0 讨论(0)
  • 2020-12-30 03:54

    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);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-30 04:10

    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.

    0 讨论(0)
提交回复
热议问题