java - spring boot中各种数据不匹配如何处理jackson反序列化错误

标签 java spring-mvc spring-boot exception-handling jackson

我知道这里有一些关于如何解析 ENUM、如何解析自定义 JSON 结构的类似问题。但在这里我的问题是,当用户提交一些 JSON 时,如何提供更好的信息而不是预期的。

这是代码:

@PutMapping
public ResponseEntity updateLimitations(@PathVariable("userId") String userId,
                                        @RequestBody LimitationParams params) {
  Limitations limitations = user.getLimitations();
  params.getDatasets().forEach(limitations::updateDatasetLimitation);
  params.getResources().forEach(limitations::updateResourceLimitation);
  userRepository.save(user);
  return ResponseEntity.noContent().build();
}

我期望的请求正文是这样的:
{
  "datasets": {"public": 10},
  "resources": {"cpu": 2}
}

但是当他们提交这样的东西时:
{
  "datasets": {"public": "str"}, // <--- a string is given
  "resources": {"cpu": 2}
}

响应将在日志中显示如下内容:
400 JSON parse error: Cannot deserialize value of type `java.lang.Integer` from String "invalid": not a valid Integer value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.lang.Integer` from String "invalid": not a valid Integer value

在 [来源: (PushbackInputStream);行:1,列:23](通过引用链:com.openbayes.api.users.LimitationParams["datasets"]->java.util.LinkedHashMap["public"])

但我想要的是更易读的信息。

我尝试使用 ExceptionHandlercom.fasterxml.jackson.databind.exc.InvalidFormatException但它不起作用。

最佳答案

您可以编写 Controller 通知来捕获异常并返回相应的错误响应。

以下是 spring boot 中的 Controller 建议示例:

@RestControllerAdvice
public class ControllerAdvice {
    @ExceptionHandler(InvalidFormatException.class)
    public ResponseEntity<ErrorResponse> invalidFormatException(final InvalidFormatException e) {
        return error(e, HttpStatus.BAD_REQUEST);
    }

    private ResponseEntity <ErrorResponse> error(final Exception exception, final HttpStatus httpStatus) {
        final String message = Optional.ofNullable(exception.getMessage()).orElse(exception.getClass().getSimpleName());
        return new ResponseEntity(new ErrorResponse(message), httpStatus);
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
public class ErrorResponse {
    private String errorMessage;
}

关于java - spring boot中各种数据不匹配如何处理jackson反序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52196053/

相关文章:

java - 如何在Android Vision API中设置全屏?

java - 具有不同布局的多个回收器 View

java - 寻找可以插入 Spring MVC 应用程序的 CMS

java - Spring boot RESTful 服务作为 WAR 而不是 JAR

spring-boot - Docker - 为 root 用户配置了空密码的 mysql

JavaMailSenderImpl 配置一个电子邮件地址并使用另一个电子邮件地址作为 MimeMessageHelper.setFrom 但表示权限问题

java - flyway:migrate 不创建表

java - 客户端发送的请求在语法上不正确。在spring中使用@RequestParam

javascript - GraphQL 和 Hibernate (ORM)

java - 带有 Spring Boot 1.5.* 的 Elastic Search 5.4