【问题标题】:Springboot: How to override default JSON response structure in case of any type failures?Spring Boot:如何在任何类型失败的情况下覆盖默认的 JSON 响应结构?
【发布时间】:2021-07-12 16:48:54
【问题描述】:

在我的 Springboot(2.x.x) 应用程序中,在使用 REST Controller 时,我需要处理两种类型的故障

  1. 自定义验证失败,这里我可以根据需要生成任何 Json Response 结构(即我需要的任何字段)

  2. Springboot 的默认验证失败(下面给出了几个例子,还有更多)。在这里,它生成 5xx 或 4xx 以及 json 响应中的默认几个字段。如何在应用层覆盖它并匹配我的自定义失败 JSON 响应?

            MissingServletRequestPartException.class, //it will be thrown when one of form param is missing
            MissingServletRequestParameterException.class, //it will be thrown when one of request param is missing
            MethodArgumentNotValidException.class, //it will be thrown when form json param value is not valid
            MethodArgumentTypeMismatchException.class, //it will be thrown when request param type value is mismatched
            ConstraintViolationException.class, // it will be thrown when any of request param is not valid
   

【问题讨论】:

    标签: java json spring spring-boot spring-restcontroller


    【解决方案1】:

    您可以验证您的请求并为每个验证错误抛出自定义异常。

    创建异常处理程序,它会为您捕获异常并为您完成必要的工作。

    可以找到spring错误处理的代码sn-phere

    【讨论】:

      猜你喜欢
      • 2015-08-30
      • 2014-09-15
      • 2019-11-16
      • 2014-12-12
      • 2019-08-13
      • 2016-06-06
      • 2019-05-09
      • 2019-08-29
      • 1970-01-01
      相关资源
      最近更新 更多