码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • springboot自定义全局异常,非空等参数校验异常


    1. @ApiOperation(value = "新增账号")
    2. @PostMapping("/addAccount")
    3. public Result addAccount(@Valid @RequestBody AddAccountVo vo) {
    4. usrAccountService.addAccount(vo);
    5. return Result.success(RespCode.SUCCESS);
    6. }
    7. @NotBlank(message = "mobile不能为空")
    8. @ApiModelProperty(value = "手机号")
    9. private String mobile;
    10. @ApiModelProperty(value = "邮箱")
    11. private String email;
    12. @ApiModelProperty(value = "部门名称-拼接")
    13. private String deptIdListName;
    14. @ApiModelProperty(value = "启动可见权限数据集合")
    15. @NotEmpty(message = "enabledList不能用空")
    16. private List enabledList;
    17. public List getEnable
    18.  自定义全局异常处理类: 

      1. @Order(-1000)
      2. @Configuration
      3. public class ExceptionHandler implements HandlerExceptionResolver {
      4. private static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);
      5. @Override
      6. public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
      7. Exception ex) {
      8. ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
      9. HashMap result = new HashMap<>();
      10. result.put("success",false);
      11. if (ex instanceof ServiceException) {
      12. result.put("code", ((ServiceException) ex).getCode());
      13. result.put("msg", StringUtils.hasLength(((ServiceException) ex).getMsg())
      14. ? ((ServiceException) ex).getMsg(): ex.getMessage() );
      15. if(StringUtils.hasLength(((ServiceException) ex).getData())){
      16. result.put("data", JSONObject.parse(((ServiceException) ex).getData()));
      17. }
      18. result.put("timestamp",System.currentTimeMillis());
      19. result.put("traceId",((ServiceException) ex).getTraceId());
      20. LOGGER.error("业务异常:" + (StringUtils.hasLength(((ServiceException) ex).getMsg())
      21. ? ((ServiceException) ex).getMsg(): ex.getMessage()));
      22. }else if (ex instanceof MethodArgumentNotValidException) {
      23. result.put("code", 9999);
      24. result.put("msg", ((MethodArgumentNotValidException) ex).getBindingResult().getFieldError().getDefaultMessage());
      25. result.put("timestamp",System.currentTimeMillis());
      26. result.put("traceId", UUID.randomUUID().toString().replace("-", ""));
      27. LOGGER.info("参数异常RebuildServiceException:{}" , result);
      28. } else {
      29. ex.printStackTrace();
      30. result.put("code", RespCode.END.getCode());
      31. result.put("msg", RespCode.END.getMsg());
      32. result.put("timestamp",System.currentTimeMillis());
      33. result.put("traceId", UUID.randomUUID().toString().replace("-", ""));
      34. LOGGER.error(RespCode.END.getMsg());
      35. }
      36. response.setContentType(MediaType.APPLICATION_JSON_VALUE);
      37. response.setCharacterEncoding("UTF-8");
      38. response.setHeader("Cache-Control", "no-cache, must-revalidate");
      39. try {
      40. modelAndView.addAllObjects(result);
      41. } catch (Exception e) {
      42. LOGGER.error("#与客户端通讯异常:" + e.getMessage(), e);
      43. }
      44. return modelAndView;
      45. }

      自定义业务异常类

      1. public class ServiceException extends RuntimeException {
      2. private static final long serialVersionUID = 3653415555548581494L;
      3. private String code;
      4. private String msg;
      5. private String data;
      6. private String traceId= UUID.randomUUID().toString().replace("-", "");
      7. private RespCode respCode;
      8. public RespCode getRespCode() {
      9. return respCode;
      10. }
      11. public String getCode() {
      12. return code;
      13. }
      14. public void setCode(String code) {
      15. this.code = code;
      16. }
      17. public String getMsg() {
      18. return msg;
      19. }
      20. public void setMsg(String msg) {
      21. this.msg = msg;
      22. }
      23. public String getData() {
      24. return data;
      25. }
      26. public void setData(String data) {
      27. this.data = data;
      28. }
      29. public void setRespCode(RespCode respCode) {
      30. this.respCode = respCode;
      31. }
      32. @SuppressWarnings("unused")
      33. private ServiceException() {
      34. }
      35. public ServiceException(String msg, Throwable e) {
      36. super(msg, e);
      37. this.msg = msg;
      38. }
      39. public ServiceException(String msg) {
      40. super(msg);
      41. this.msg = msg;
      42. }
      43. public ServiceException(RespCode respCode) {
      44. super(respCode.getCode() + respCode.getMsg());
      45. this.code = respCode.getCode();
      46. this.msg = respCode.getMsg();
      47. this.respCode=respCode;
      48. }
      49. public ServiceException(String data, RespCode respCode) {
      50. super(respCode.getCode() + respCode.getMsg());
      51. this.code = respCode.getCode();
      52. this.msg = respCode.getMsg();
      53. this.data=data;
      54. this.respCode=respCode;
      55. }
      56. public ServiceException(RespCode respCode, Object... moreMsg) {
      57. super(respCode.getCode() + String.format(respCode.getMsg(), moreMsg));
      58. this.code = respCode.getCode();
      59. try {
      60. msg = String.format(respCode.getMsg(), moreMsg);
      61. } catch (Exception e) {
      62. msg = respCode.getMsg();
      63. }
      64. }
      65. public ServiceException(String data, RespCode respCode, Object... moreMsg) {
      66. super(respCode.getCode() + respCode.getMsg());
      67. this.code = respCode.getCode();
      68. try {
      69. msg = String.format(respCode.getMsg(), moreMsg);
      70. } catch (Exception e) {
      71. msg = respCode.getMsg();
      72. }
      73. this.data=data;
      74. this.respCode=respCode;
      75. }
      76. public String getTraceId() {
      77. return traceId;
      78. }
      79. public void setTraceId(String traceId) {
      80. this.traceId = traceId;
      81. }
      1. /**
      2. * 统一返回结果
      3. * @author: jly
      4. * @date: 2023/4/6
      5. */
      6. public class Result {
      7. private String code;
      8. private String msg;
      9. private String traceId;
      10. private Long timestamp;
      11. private T data;
      12. public String getCode() {
      13. return code;
      14. }
      15. public void setCode(String code) {
      16. this.code = code;
      17. }
      18. public String getMsg() {
      19. return msg;
      20. }
      21. public void setMsg(String msg) {
      22. this.msg = msg;
      23. }
      24. public String getTraceId() {
      25. return traceId;
      26. }
      27. public void setTraceId(String traceId) {
      28. this.traceId = traceId;
      29. }
      30. public Long getTimestamp() {
      31. return timestamp;
      32. }
      33. public void setTimestamp(Long timestamp) {
      34. this.timestamp = timestamp;
      35. }
      36. public T getData() {
      37. return data;
      38. }
      39. public void setData(T data) {
      40. this.data = data;
      41. }
      42. public static Result success(T body) {
      43. Result res = new Result<>();
      44. res.setCode(RespCode.SUCCESS.getCode());
      45. res.setMsg(RespCode.SUCCESS.getMsg());
      46. res.setData(body);
      47. res.setTraceId(UUID.randomUUID().toString().replace("-", ""));
      48. res.setTimestamp(System.currentTimeMillis());
      49. return res;
      50. }
      51. public static Result fail(T body) {
      52. Result res = new Result<>();
      53. res.setCode(RespCode.SUCCESS.getCode());
      54. res.setMsg(RespCode.SUCCESS.getMsg());
      55. res.setData(body);
      56. res.setTraceId(UUID.randomUUID().toString().replace("-", ""));
      57. res.setTimestamp(System.currentTimeMillis());
      58. return res;
      59. }
      60. }
      1. /**
      2. * 返回结果码
      3. * * @author: jly
      4. * @date: 2023/4/6
      5. */
      6. public enum RespCode {
      7. /**
      8. * 操作成功
      9. */
      10. SUCCESS("0000", "操作成功"),
      11. PARAM_ILLEGAL("0001", "参数[%s]非法,%s"),
      12. END("0002", "系统繁忙,请稍后再试"),
      13. PARAMETER_FAIL("0003", "参数缺失,%s"),
      14. ;
      15. private String code;
      16. private String msg;
      17. RespCode(String code, String msg) {
      18. this.code = code;
      19. this.msg = msg;
      20. }
      21. public static RespCode getRespByCode(String code) {
      22. if (code == null) {
      23. return null;
      24. }
      25. for (RespCode resp : values()) {
      26. if (resp.getCode().equals(code)) {
      27. return resp;
      28. }
      29. }
      30. throw new IllegalArgumentException("无效的code值!code:" + code);
      31. }
      32. public String getCode() {
      33. return code;
      34. }
      35. public String getMsg() {
      36. return msg;
      37. }
      38. public boolean isSuccess(String code) {
      39. return Objects.equals(code, this.code);
      40. }
      41. }
       
      
      可能用到的依赖
      
          org.hibernate.validator
          hibernate-validator
          6.2.0.Final
      
      
          fa.hiveware
          hiveware-cmn-contract
          1.0
      
    19. 相关阅读:
      Python 多进程编程《*》: 共享内存 shared ctypes objects & sharedctypes 模块
      【EasyPoi】SpringBoot使用EasyPoi自定义模版导出Excel
      C#【必备技能篇】生成公共属性代码{get;set;}的快捷方法
      什么是生物识别技术?它是如何用于安全领域的?
      spark sql官网优化指南
      python中字典的循环遍历的方式
      【github actions】部署前端项目
      智能设计-阿里巴巴Banner设计
      12 | JAVASE高级应用-集合
      -元素之和-
    20. 原文地址:https://blog.csdn.net/jialiuyang/article/details/133941822
      • 最新文章
      • 攻防演习之三天拿下官网站群
        数据安全治理学习——前期安全规划和安全管理体系建设
        企业安全 | 企业内一次钓鱼演练准备过程
        内网渗透测试 | Kerberos协议及其部分攻击手法
        0day的产生 | 不懂代码的"代码审计"
        安装scrcpy-client模块av模块异常,环境问题解决方案
        leetcode hot100【LeetCode 279. 完全平方数】java实现
        OpenWrt下安装Mosquitto
        AnatoMask论文汇总
        【AI日记】24.11.01 LangChain、openai api和github copilot
      • 热门文章
      • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
        奉劝各位学弟学妹们,该打造你的技术影响力了!
        五年了,我在 CSDN 的两个一百万。
        Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
        面试官都震惊,你这网络基础可以啊!
        你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
        心情不好的时候,用 Python 画棵樱花树送给自己吧
        通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
        13 万字 C 语言从入门到精通保姆级教程2021 年版
        10行代码集2000张美女图,Python爬虫120例,再上征途
      Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
      正则表达式工具 cron表达式工具 密码生成工具

      京公网安备 11010502049817号