spring controlleradvice不返回响应体?

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

我有以下几点 ControllerAdvice ,处理 JsonParseException (我用Spring和Jackson)

  1. @ControllerAdvice
  2. public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
  3. @ExceptionHandler(JsonParseException.class)
  4. public ResponseEntity<Object> handleInvalidJson(JsonParseException ex, WebRequest request){
  5. Map<String,Object> body = new LinkedHashMap<>();
  6. body.put("timestamp", LocalDateTime.now());
  7. body.put("message","Invalid Json");
  8. return new ResponseEntity(body, HttpStatus.BAD_REQUEST);
  9. }
  10. }

由于某种原因,当我向服务器发送一个错误的json请求时,它不起作用,只返回400。当我换衣服的时候 HttpStatus ,它仍然返回400,因此建议似乎没有真正运行。

dgenwo3n

dgenwo3n1#

ResponseEntityExceptionHandler 已经实现了很多不同的异常处理程序。 HttpMessageNotReadableException 是其中之一:

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

只需删除继承:

  1. @ControllerAdvice
  2. public class TestExceptionHandler {
  3. @ExceptionHandler(JsonParseException.class)
  4. public ResponseEntity<Map<String,Object>> handleInvalidJson(JsonParseException ex, WebRequest request){
  5. Map<String,Object> body = new LinkedHashMap<>();
  6. body.put("timestamp", LocalDateTime.now());
  7. body.put("message","Invalid Json");
  8. return new ResponseEntity<>(body, HttpStatus.I_AM_A_TEAPOT);
  9. }
  10. }
展开查看全部

相关问题