problem-spring-web: Handle specific reasons of HttpMessageNotReadableException

Something like this

    @ExceptionHandler
    public ResponseEntity<Problem> onHttpMessageNotReadable(final HttpMessageNotReadableException e) throws Throwable {
        final Throwable cause = e.getCause();
        if (cause == null) {
            return onException(e);
        } else if (cause instanceof JsonParseException) {
            return onParseException((JsonParseException) cause);
        } else if (cause instanceof JsonMappingException) {
            return onMappingException((JsonMappingException) cause);
        } else {
             ...
        }
    }

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 15 (5 by maintainers)

Commits related to this issue

Most upvoted comments

I was hoping there was a more elegant way of hanlding exceptions instead of having to do below

@ExceptionHandler
    public ResponseEntity<Problem> onHttpMessageNotReadable(final HttpMessageNotReadableException e) throws Throwable {
        final Throwable cause = e.getCause();
        if (cause == null) {
            return onException(e);
        } else if (cause instanceof JsonParseException) {
            return onParseException((JsonParseException) cause);
        } else if (cause instanceof JsonMappingException) {
            return onMappingException((JsonMappingException) cause);
        } else {
             ...
        }
    }

Alternatively you can throw and catch it. So you don’t need the instanceof checks.

If you throw an exception from a ExceptionHandler, will it be catched by any ControllerAdvice again? I think I’ve seen JsonParseException (not wrapped inside a HttpMessageNotReadableException), which would be cool for this.