【问题标题】:Spring Boot human readable error messages after JSON parsing errorJSON解析错误后的Spring Boot人类可读错误消息
【发布时间】:2021-07-07 13:19:47
【问题描述】:

我有一个使用 Spring Boot 编写的 REST API。现在我想加强错误处理。如果用户发送无效的 JSON 或我无法反序列化到我的 DTO 的 JSON,我会通知用户究竟出了什么问题,例如意外的属性名称、类型等。我仍然不想公开有关实现的任何信息(例如堆栈跟踪、类名)。

默认 Spring 实现返回

InvalidFormatException: Cannot deserialize value of type `java.lang.Integer` from String \"aaa\": not a valid Integer value\n at [Source: (PushbackInputStream); line: 10, column: 19]
 (through reference chain: com.yell.statementofwork.model.StatementOfWorkCompletionDtoSe[\"purchasedProducts\"]->java.util.ArrayList[0]->com.yell.statementofwork.model.PurchasedProductDtoSe[\"quantity\"])",

这几乎是好的,但我更愿意从中删除有关类的信息。 你有什么建议吗?

【问题讨论】:

标签: java json spring spring-boot jackson


【解决方案1】:

您可以创建自己的自定义 ConstraintValidator 并使用相应的注释来注释您的 DTO 对象

您可以在此处找到示例 - http://dolszewski.com/spring/custom-validation-annotation-in-spring/

附:该示例为一个字段使用注释,但您可以在整个班级使用它

【讨论】:

    【解决方案2】:

    在 Spring Boot REST API 中处理不同类型错误的最简洁方法是使用 Spring AOP。 首先,让我们创建一个自定义的 Exception 类

    public class InvalidFormatException extends RuntimeException {
    
        private final String message;
        private final List<String> data;
    
        // getters , setters and constructors
    }
    

    然后创建一个错误响应模型类。这个模型类将提供一个 JSON 结构,说明在发生异常时应该返回给用户的内容

    public class ErrorResponseModel {
        
        String code;
        String type;
        String message;
        List<String> data;
    
        // getters, setters, and constructor
    }
    

    然后使用 spring AOP 为你的控制器创建一个自定义异常处理程序

    @ControllerAdvice
    public class ControllerExceptionHandler {
    
        @ExceptionHandler(InvalidFormatException.class)
        public ResponseEntity<ErrorResponseModel> badRequestException(InvalidFormatException ex, WebRequest request) {
            return new ResponseEntity<>(new ErrorResponseModel(ex.getMessage(), ex.getData()),
                    HttpStatus.BAD_REQUEST);
        }
    }
    

    您可以在此类中添加和处理更多类似这样的错误类型。 现在,每当您抛出异常时,它都会在此处被拦截,并将自定义错误响应发送回给用户。

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 1970-01-01
      • 2019-07-26
      • 2022-07-16
      • 2018-12-26
      • 2015-04-26
      • 2021-11-18
      • 2016-11-07
      • 1970-01-01
      相关资源
      最近更新 更多