问题描述
我有以下 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);
}
}