Springboot:在任何类型失败的情况下,如何覆盖默认的JSON响应结构



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

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

  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

您可以验证您的请求,并为每个验证错误抛出Custom异常。

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

你可以在这里找到春季错误处理的代码片段

最新更新