Spring ControllerAdvice 没有return 响应主体?

Spring ControllerAdvice does not return response body?

我有以下 ControllerAdvice,它处理 JsonParseException(我使用 Spring 和 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);
 }
}

出于某种原因,当我向服务器发送错误的 json 请求时它不起作用,只有 returns 400。当我更改 HttpStatus 时,它仍然 returns 400 所以看起来这个建议并不是真的 运行.

ResponseEntityExceptionHandler 已经实现了很多不同的 ExceptionHandlers。 HttpMessageNotReadableException就是其中之一:

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

只需删除继承:

@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);
    }
}