0

我有以下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 请求时它不起作用,只返回 400。当我更改 时HttpStatus,它仍然返回 400,所以看起来建议并没有真正运行。

4

1 回答 1

1

ResponseEntityExceptionHandler已经实现了很多不同的异常处理程序。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);
    }
}
于 2021-01-27T15:36:41.563 回答