首页 > Java > java教程 > 正文

如何在SpringBoot中实现统一异常处理

WBOY
发布: 2023-05-10 22:01:04
转载
1299人浏览过

场景:针对异常处理,我们原来的做法是一般在最外层捕获异常即可,例如在Controller中

@Controller
public class HelloController {
 
  private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
 
  @GetMapping(value = "/hello")
  @ResponseBody
  public Result hello() {
    try {
      //TODO 具体的逻辑省略……
    } catch (Exception e) {
      logger.error("hello接口异常={}", e);
      return ResultUtil.success(-1, "system error", null);
    }
    return ResultUtil.success(0, "success", null);
  }
}
登录后复制

这样的话也能解决部分问题,但是无法获取到自己指定的异常,引入全局统一异常处理的话将会极大的改善代码,减少冗余代码的产生。

自定义异常类:注意要继承自RuntimeException而不是Exception,继承自Exception的话,当抛出自定义异常时spring事务不会回滚

public class GlobalException extends RuntimeException {
 
  private Integer code; //因为我需要将异常信息也返回给接口中,所以添加code区分
 
  public GlobalException(Integer code,String message) {
    super(message);  //把自定义的message传递个异常父类
    this.code = code;
  }
 
  public Integer getCode() {
    return code;
  }
 
  public void setCode(Integer code) {
    this.code = code;
  }
}
登录后复制

自定义统一异常处理器:比较关键的两个注解@ControllerAdvice、@ExceptionHandler

@ControllerAdvice
public class ExceptionHandle {
 
  @ResponseBody  //因为我需要将抛出的异常返回给接口,所以加上此注解
  @ExceptionHandler
  public Result handle(Exception e) {
    if (e instanceof GlobalException) {
      GlobalException ge = (GlobalException) e;
      return ResultUtil.success1(ge.getCode(), ge.getMessage());
    }
    return ResultUtil.success1(-1, "system error!");
  }
 
}
登录后复制

写个测试类测试下

@GetMapping(value = "/hello1")
@ResponseBody
public Result hello(@RequestParam(value = "age", defaultValue = "50", required = false) Integer age) throws GlobalException {
  if (age < 10) {
    throw new GlobalException(ConstantEnum.LESS10.getCode(), ConstantEnum.LESS10.getMsg());
  } else if (age > 50) {
    throw new GlobalException(ConstantEnum.MORE50.getCode(), ConstantEnum.MORE50.getMsg());
  } else {
    return ResultUtil.success1(0, "success");
  }
}
登录后复制

把code、message封装在了ConstantEnum枚举里面,方便统一维护

public enum ConstantEnum {
 
  ERROR(-1, "system error!"),
  SUCCESS(100, "success"),
  LESS10(101, "自定义异常信息-我小于10岁"),
  MORE50(5001, "自定义异常信息-我大于50岁");
 
  private Integer code;
  private String msg;
 
  public Integer getCode() {
    return code;
  }
 
  public String getMsg() {
    return msg;
  }
 
  ConstantEnum(Integer code, String msg) {
    this.code = code;
    this.msg = msg;
  }
}
登录后复制

如何在SpringBoot中实现统一异常处理

以上就是如何在SpringBoot中实现统一异常处理的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:亿速云网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号