0

I have the following ControllerAdvice, that handles JsonParseException (I use Spring and Jackson)

@ControllerAdvice
public class ControllerExceptionHandler  extends ResponseEntityExceptionHandler {

  @ExceptionHandler(JsonParseException.class)
  public ResponseEntity<Object> handleInvalidJson(JsonParseException ex, WebRequest request){
    Map<String,Object> body = new LinkedHashMap<>();
    body.put("timestamp", LocalDateTime.now());
    body.put("message","Invalid Json");

    return new ResponseEntity(body, HttpStatus.BAD_REQUEST);
 }
}

Fore some reason, It doesn't work when I send a bad json request to the server, only returns 400. When I change the HttpStatus, it still returns 400 so it seems like the advice doesn't really run.

Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
jhthewow
  • 133
  • 1
  • 3
  • 12

1 Answers1

2

ResponseEntityExceptionHandler already implements a lot of different ExceptionHandlers. HttpMessageNotReadableException is one of them:

else if (ex instanceof HttpMessageNotReadableException) {
            HttpStatus status = HttpStatus.BAD_REQUEST;
            return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, headers, status, request);
        }

Simply remove the inheritance:

@ControllerAdvice
public class TestExceptionHandler {

    @ExceptionHandler(JsonParseException.class)
    public ResponseEntity<Map<String,Object>> handleInvalidJson(JsonParseException ex, WebRequest request){
        Map<String,Object> body = new LinkedHashMap<>();
        body.put("timestamp", LocalDateTime.now());
        body.put("message","Invalid Json");

        return new ResponseEntity<>(body, HttpStatus.I_AM_A_TEAPOT);
    }
}
peterulb
  • 2,869
  • 13
  • 20
  • 1
    Not working for me. I set the headers in @ExceptionHandler method and those headers come ok. No matter what I do the body is always empty. – user3852017 Feb 22 '22 at 08:50
  • 1
    @user3852017 I'm facing the same issue, It looks like it could set the status but not the response body. I'm not even using any inheritance. – mike May 05 '22 at 22:11
  • It works for me. I want to keep default response body and just modify the status code. I use "response.sendError(HttpStatus.BAD_REQUEST.value());" only and don't extend ResponseEntityExceptionHandler. – emeraldhieu Sep 09 '22 at 16:31
  • Same problem here. Removing inheritance did not help. – Jarzka Feb 28 '23 at 16:44