我有一个使用 ControllerAdvice
的 Spring Boot REST 应用程序和 ExceptionHandlers
.我正在使用 Jackson
作为我的序列化/反序列化。我正在使用 PostMan
作为我的客户,当我发送不同的错误(例如无效输入、错误的 JSON 语法等)时……Jackson 会抛出某些异常。目前,我有一个 (1) ExceptionHandler
明确说明每种类型的异常,例如 MismatchedInputException
, InvalidFormatException
, InvalidDentinitionException
...这些都是JsonProcsessingException
的所有形式.
有没有办法只抓 JsonProcessingException
和它所有的 child ?我根据异常类型返回不同的消息/状态代码。因此,如果抛出与序列化相关的异常,我希望发回某个错误消息。
最佳答案
您应该在 @ControllerAdvice 类中创建此方法并验证您要管理哪些异常以返回不同的消息/状态代码。
@ExceptionHandler({InvalidFormatException.class, MismatchedInputException.class})
public void handlerIllegalArgumentException(JsonProcessingException exception,
ServletWebRequest webRequest) throws IOException {
if(exception instanceof InvalidFormatException) {
LOGGER.error(exception.getMessage(), exception);
webRequest.getResponse().sendError(HttpStatus.CONFLICT.value(), exception.getMessage());
} else if (exception instanceof MismatchedInputException) {
LOGGER.error(exception.getMessage(), exception);
webRequest.getResponse().sendError(HttpStatus.BAD_REQUEST.value(), exception.getMessage());
}
}
关于spring-mvc - 如何在 Spring 中捕获大量 Jackson Exceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53302286/