spring controlleradvice不返回响应体?

qrjkbowd  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(435)

我有以下几点 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,因此建议似乎没有真正运行。

dgenwo3n

dgenwo3n1#

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

相关问题