首页 > 解决方案 > Springboot:如何在任何类型失败的情况下覆盖默认的 JSON 响应结构?

问题描述

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

  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
   

标签: javajsonspringspring-bootspring-restcontroller

解决方案


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

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

您可以在此处找到用于弹簧错误处理的代码片段


推荐阅读