如何在 Spring 捕获大量 Jackson 异常?

Dix*_*vey 5 spring-mvc jackson spring-boot

我有一个使用ControllerAdvice和的 Spring Boot REST 应用程序ExceptionHandlers。我正在使用Jackson我的序列化/反序列化。我正在使用PostMan我的客户端,当我发送不同的错误(例如无效输入、错误的 JSON 语法等)时... Jackson 会抛出某些异常。目前,我有一个 (1)ExceptionHandler明确声明每种类型的异常,例如MismatchedInputExceptionInvalidFormatExceptionInvalidDentinitionException...这些都是JsonProcsessingException.

有没有办法只捕获JsonProcessingException它的所有孩子?我根据异常类型返回不同的消息/状态代码。因此,如果引发与序列化相关的异常,我希望发回特定的错误消息。

Jon*_*ohx 4

您应该在 @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());
    }
}
Run Code Online (Sandbox Code Playgroud)