Syzak
Syzak

Reputation: 153

How to handle MethodArgumentNotValidException

I would like to handle exception thrown by validator.

I've made exception handler with ControllerAdvice annotation. It handles other exceptions but not MethodArgumentNotValidException.

Exception handler

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value
        = {ResourceNotFoundException.class, EntityNotFoundException.class})
    protected ResponseEntity<Object> handleNotFound(
        RuntimeException ex, WebRequest request) {

    APIException apiException = new APIException(HttpStatus.NOT_FOUND,
            ex.getMessage(), request);

    return handleExceptionInternal(ex, apiException,
            new HttpHeaders(), apiException.getStatus(), request);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid
            (MethodArgumentNotValidException ex,
                 HttpHeaders headers, HttpStatus status, WebRequest request)     {
        APIException apiException = new APIException(HttpStatus.BAD_REQUEST,
            ex.getMessage(), request);

        return handleExceptionInternal(ex, apiException,
            new HttpHeaders(), apiException.getStatus(), request);
    }
}

Validated class (without getters/setters etc.)

public class ClassQuery {
    @Min(1)
    private Integer minYear;
    @Min(1)
    private Integer year;
    @Min(1)
    private Integer maxYear;
    private String name;
    private String profile;
}

Rest api controller

@GetMapping
public Page<Class> getClasses(@Valid ClassQuery classQuery, Pageable pageable) {
    return classService.getClasses(classQuery, pageable);
}

Api Exception (without getters/setters etc.)

public class APIException {
    private Date timestamp;
    private HttpStatus status;
    private String message;
    private String path;

    public APIExceptionMessage(HttpStatus status, String message, WebRequest request) {
            this();
            this.status = status;
            this.message = message;
            this.path = getRequestURI(request);
    }
}

Currently I'm getting an empty response with BAD_REQUEST http status from validator while other exceptions are handled correctly. I've also tried no extending ResponseEntityExceptionHandler and handle it with @ExceptionHandler but it was ignoring my response body, in response it gave default error message. I'm not getting any error.

Upvotes: 4

Views: 12284

Answers (1)

Omkar Manjrekar
Omkar Manjrekar

Reputation: 103

This may be a bit too late.

I had the same problem where MethodArgumentNotValidException was not being handled by the class annotated as ControllerAdvice. In my case, I wanted to serialize and send a custom ErrorDTO Object as JSON to the HTTP Client.

Solution: MethodArgumentNotValidException should be imported from org.springframework.web.bind.MethodArgumentNotValidException.

Upvotes: 3

Related Questions