How to catch a lot of Jackson Exceptions in Spring?

Viewed 3140

I have a Spring Boot REST application that uses ControllerAdvice and ExceptionHandlers. I'm using Jackson as my serialization/deserialization. I'm using PostMan as my client and when I send in different errors such as invalid inputs, bad JSON syntax etc... Jackson throws certain exceptions. Currently, I have an (1) ExceptionHandler that explicitly states each type of exception such as MismatchedInputException, InvalidFormatException, InvalidDentinitionException...these are all forms of JsonProcsessingException.

Is there a way to just catch JsonProcessingException and all its children? I return different messages/status codes depending on the types of exceptions. So if exception related to serialization is thrown I want a certain error message sent back.

1 Answers

You should create this method in @ControllerAdvice class and verify what exceptions you want to manage in order to return different messages/status codes .

@ExceptionHandler({InvalidFormatException.class, MismatchedInputException.class})
public void handlerIllegalArgumentException(JsonProcessingException exception,
                                            ServletWebRequest webRequest) throws IOException {
    if(exception instanceof InvalidFormatException) {
        LOGGER.error(exception.getMessage(), exception);
        webRequest.getResponse().sendError(HttpStatus.CONFLICT.value(), exception.getMessage());
    } else if (exception instanceof MismatchedInputException) {
        LOGGER.error(exception.getMessage(), exception);
        webRequest.getResponse().sendError(HttpStatus.BAD_REQUEST.value(), exception.getMessage());
    }
}
Related