Spring ControllerAdvice 不返回响应体?

问题描述

我有以下 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,所以看起来这个建议没有真的跑了。

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...