温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在SpringBoot中实现统一异常处理

发布时间:2021-06-11 15:43:33 来源:亿速云 阅读:177 作者:Leah 栏目:编程语言

怎么在SpringBoot中实现统一异常处理,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

场景:针对异常处理,我们原来的做法是一般在最外层捕获异常即可,例如在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中实现统一异常处理的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI