ARU
ARU

Reputation: 147

Spring ResponseEntityExceptionHandler does not resolve override messages

I am overriding the BindException by extending ResponseEntityExceptionHandler.

I supplied my custom messages in property bundle . However, its not getting recognized by ResponseEntityExceptionHandler.

It does resolve for TypeMistMatch on controller request parameters. But it does not inside ResponseEntityExceptionHandler.

Am I missing something?

@Component
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleBindException(final org.springframework.validation.BindException ex,
            final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
        logger.info(ex.getClass().getName());
        //
        final List<String> errors = new ArrayList<String>();
        for (final FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.add(error.getField() + ": " + error.getDefaultMessage());
        }
        for (final ObjectError error : ex.getBindingResult().getGlobalErrors()) {
            errors.add(error.getObjectName() + ": " + error.getDefaultMessage());
        }
        final ErrorMessage apiError = new ErrorMessage(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors.toString());
        return new ResponseEntity<>(apiError, new HttpHeaders(), HttpStatus.BAD_REQUEST);
    }

}

Msg.properties

typeMismatch.demoPojo.instant= Supposed to be a date
typeMismatch.instant=Instant field
typeMismatch.java.time.Instant=Instant type

Upvotes: 2

Views: 6525

Answers (3)

Eduardo Nobre
Eduardo Nobre

Reputation: 200

Included anotation "@Order(Ordered.HIGHEST_PRECEDENCE)" in my @ControlerAdvice solved my problema that it's same with yours.

enter image description here

Upvotes: 2

Gajendra Bora
Gajendra Bora

Reputation: 51

You need to define getters in ErrorMessage class.

Upvotes: 1

Raquel Casado Dias
Raquel Casado Dias

Reputation: 21

I've followed that tutorial as well and the error isn't in this class. It's in the class apiError. You should generate getters and setters, something that wasn't shown on the tutorial.

Tutorial link: http://www.baeldung.com/global-error-handler-in-a-spring-rest-api

Upvotes: 0

Related Questions