首先引入springboot包

compile group: 'org.springframework.boot', name: 'spring-boot-starter-validation'

然后创建一个实体类

@Setter
@Getter
public class CountryBo {@NotNull(message = "{region.error.null}")@Length(max = 10,message = "{region.error.length}")private String region;@NotNull(message = "{countryCode.error.null}")@Length(max = 10,message = "{countryCode.error.length}")private String countryCode;
}
  • 这里使用了消息文件直接把ValidationMessages.properties文件放到resource目录下,也可通过springboot的配置自定义文件名
region.error.null=region is not allow null
region.error.length=More than the length of region
countryCode.error.null=region is not allow null
countryCode.error.length=More than the length of region
id.error.null=id is not allow null
id.error.length=More than the length of id

创建Controller类

@RestController
@Api(tags = "测试类")
@Slf4j
public class TestController {@Autowiredprivate TestService testService;@GetMapping("/testsql")@ApiOperation("测试SqlServer")public JsonResult test(@Valid CountryBo contry){JsonResult jsonResult = new JsonResult();try{jsonResult.setData(testService.test(contry));return jsonResult;}catch (NecServiceExcepiton e){log.error("excute failed :{}",e.getMessage());jsonResult.setCode(e.getErrorCode());jsonResult.setMsg("处理失败");return jsonResult;}catch (Exception e){log.error("excute failed :{}",e.getMessage());jsonResult.setCode("90001");jsonResult.setMsg("处理异常");return jsonResult;}}@GetMapping("/testMongo")@ApiOperation("测试Mongo")@ApiParam()public JsonResult testMongo(@Valid PartsBo partsBo){JsonResult jsonResult = new JsonResult();try{jsonResult.setData(testService.testMongo(partsBo));return jsonResult;}catch (NecServiceExcepiton e){log.error("excute failed :{}",e.getMessage());jsonResult.setCode(e.getErrorCode());jsonResult.setMsg("处理失败");return jsonResult;}catch (Exception e){log.error("excute failed :{}",e.getMessage());jsonResult.setCode("90001");jsonResult.setMsg("处理异常");return jsonResult;}}}

重写ResponseEntityExceptionHandler类的handleBindException(重点)

@ControllerAdvice
public class ValidatorHandlerAdvice extends ResponseEntityExceptionHandler {@Overrideprotected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {String message = "";JsonResult jsonResult = new JsonResult();for(ObjectError error:ex.getBindingResult().getAllErrors()){jsonResult.setCode("V0001");jsonResult.setMsg(error.getDefaultMessage());}return new ResponseEntity<Object>(jsonResult, status);}
}
  • 看源码我们能知道出现验证异常的时候是执行的handleBindException这个方法

springboot validation 统一返回错误信息相关推荐

  1. null?对象?异常?到底应该如何返回错误信息

    null?对象?异常?到底应该如何返回错误信息 参考文章: (1)null?对象?异常?到底应该如何返回错误信息 (2)https://www.cnblogs.com/dsj2016/p/748208 ...

  2. ios请求php接口失败,laravel,php_iOS调用Laravel接口返回错误信息,laravel,php,ios - phpStudy...

    iOS调用Laravel接口返回错误信息 iOS端代码如下: AFHTTPRequestOperationManager *manage = [[AFHTTPRequestOperationManag ...

  3. 配置错误:未能使用提供程序“RsaProtectedConfigurationProvider”进行解密。提供程序返回错误信息为: 打不开 RSA 密钥容器。...

    http://www.cnblogs.com/jiaruistone/articles/1441634.html 在asp.net2.0中新增了对web.config中的部分数据进行加密的功能,可以使 ...

  4. 发生了Post错误:错误代码40005,微信返回错误信息:invalid file type

    给客户部署 PxxCms, 使用群发功能发送图文的的时候提示: 发生了Post错误:错误代码40005,微信返回错误信息:invalid file type, 没学过php伤不起 ... Google ...

  5. Django rest framework 返回错误信息 __str__ returned non-string (type NoneType)

    Django rest framework 返回错误信息 str returned non-string (type NoneType) 错误信息如下: 此时点击右上角的admin,把帐号退掉,然后在 ...

  6. 【uniapp小程序】安卓手机与苹果手机的getPhoneNumber拒绝授权返回错误信息不同

    getPhoneNumber拒绝授权返回错误信息不同 开发工具和ios是getPhoneNumber:fail user deny:安卓手机是getPhoneNumber:fail:user deny ...

  7. 拨号不成功,根据返回错误信息确定故障

    拨号不成功,根据返回错误信息确定故障: 1.ror 602 The port is already open 问题:拨号网络网络由于设备安装错误或正在使用,不能进行连接 原因:RasPPPoE没有完全 ...

  8. C语言中返回错误信息的函数总结

    C语言strerror()函数:返回错误原因的描述字符串 头文件: #include <string.h> 定义函数: char * strerror(int errnum); 函数说明: ...

  9. Spring中抛出异常时,既要要返回错误信息,还要做事务回滚

    情况一:如果没有在程序中手动捕获异常,如下代码事务会回滚 @Transactional(rollbackFor = { Exception.class }) public void test() th ...

  10. mysql远程服务器返回错误404_服务器常见页面访问返回错误信息(404 500 400)表示什么意思...

    展开全部 404 500 400等是HTTP常见的几种状态码,具体相关意思解释如下:e69da5e6ba9062616964757a686964616f31333366303833 404 404页面 ...

最新文章

  1. 监管大屏系统_高速公路监管系统大屏可视化
  2. 人工智能基准(Benchmarking)再思考
  3. curl发送html邮件,使用curl命令行发送/发布xml文件
  4. mysql 连接器配置_配置连接器 - 金融分布式架构 SOFAStack - 阿里云
  5. 我擦!迅雷的代码结构竟然被扒了精光~
  6. 十五个实用的mysql语句分享_分享MySQL中实用的几种SQL语句
  7. C# 使用多个异步方法
  8. vbs学习笔记2——创建桌面快捷方式
  9. Teamcenter 入门开发系列问答(5)
  10. 新手指引,php什么是常量、变量、数组、类和对象及方法?
  11. OSI七层协议完美解读
  12. 什么是Pagerank?Pagerank算法介绍与计算公式
  13. android sdk mac 环境变量,Mac 下的SDK环境变量配置
  14. tf.data.Dataset.from_tensor_slices
  15. webpack中vender的抽离
  16. 读研2年,我选择从中科院退学转行写代码
  17. linkerd mysql_纠错帖:Zuul Spring Cloud Gateway Linkerd性能对比
  18. ffmpeg截取指定视频中的一段视频
  19. 【浏览器被劫持解决方案】https://www.hao123.com/?tn=9762xxxx2644_hao_pg
  20. 2021年【教师资格】流程全过程

热门文章

  1. HMM和DNN语音合成必备基础知识:音素和拼音的基础知识及工具初学
  2. 什么是搜索引擎?有什么作用?
  3. 贪心算法--会议安排
  4. 逃离北上广的成本越来越高了
  5. 国际市场营销知识框架图_留学热门丨伦敦里士满大学市场营销本科专业
  6. Android代码获取手机品牌、手机型号、手机唯一序列号
  7. 维基百科-D3.js
  8. 如何用ps修改图片文字颜色
  9. 微信第三方平台对接小程序发版
  10. 数据结构 与游戏背包的设计