我有一个全局异常处理程序,它可以很好地捕获从我的控制器、服务层或存储库层抛出的异常。但是,它无法捕获进入我的控制器之前发生的异常。具体来说,我有一个POST
控制器需要一个有效的 json 主体,如果实际的 json 主体格式错误,HttpMessageNotReadableException
则会抛出一个,并且我不知道在哪里处理了这个异常。响应码确实是400
。所以我的问题是,如何使用我自己的逻辑来捕获和处理在进入我的控制器之前发生的消息反序列化异常。
我的全局异常处理程序(它适用于从我的服务层抛出的异常)
@ControllerAdvice(basePackageClasses = TopologyApiController.class)
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static final String UNKNOWN_SERVER_ERROR_MSG = "Unknown server error";
@ExceptionHandler(value = {ServiceException.class})
public ResponseEntity<ErrorResponse> handleServiceException(Exception ex, WebRequest request) {
// some handling
return generateExceptionResponseEntity(errorMessage, status);
}
@ExceptionHandler(value = {Exception.class})
public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex, WebRequest request) {
return generateExceptionResponseEntity(UNKNOWN_SERVER_ERROR_MSG, HttpStatus.INTERNAL_SERVER_ERROR);
}
private ResponseEntity<ErrorResponse> generateExceptionResponseEntity(String message, HttpStatus status) {
ErrorResponse response = new ErrorResponse();
response.setMessage(message);
return ResponseEntity.status(status).body(response);
}
}
我的POST
控制器(期望 json 主体反序列化为CityInfo
对象)
@RequestMapping(value = API_BASE + "/topology/cities", method = RequestMethod.POST)
ResponseEntity<CityInfo> topologyCitiesPost(@Valid @RequestBody CityInfo body) {
CityInfo cityInfo = topologyService.addCity(body);
return ResponseEntity.status(HttpStatus.CREATED).body(cityInfo);
}
控制器需要以下形式的 json 主体,如果 json 有效,则整个代码可以正常工作。
{
"description": "string",
"name": "string",
"tag": "string"
}
但如果实际内容如下所示(例如,末尾有几个逗号),HttpMessageNotReadableException
则会抛出 an 并且不会被我的处理程序捕获。
{
"description": "this is description",
"name": "city name",
"tag": "city tag",,,,
}