我有一个全局异常处理程序,可以很好地捕获从控制器,服务层或存储库层引发的异常。但是,它无法捕获进入我的控制器之前发生的异常。具体来说,我有一个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
,并且不会被我的处理程序捕获。
{
"description": "this is description",
"name": "city name",
"tag": "city tag",,,,
}
答案 0 :(得分:0)
这: 所以我的问题是,如何使用自己的逻辑来捕获和处理在进入控制器之前发生的消息反序列化异常。
为该特定异常注释并编写一个exceptionHandler。将此添加到您的'./index.js 1:275593-275611\nCritical dependency: the request of a dependency is an expression\n ...
'asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).\nThis can impact web performance.\nAssets: \n ../assets/index.android.bundle (1.57 MiB)',
'entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.\nEntrypoints:\n main (1.57 MiB)\n ../assets/index.android.bundle\n',
'webpack performance recommendations: \nYou can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\nFor more info visit https://webpack.js.org/guides/code-splitting/'
类中:
GlobalExceptionHandler