• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot使用统一异常处理详解

springboot 搞代码 4年前 (2022-01-05) 170次浏览 已收录 0个评论

这篇文章主要为大家详细介绍了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  50) { throw new GlobalException(ConstantEnum.MORE50.getCode(), ConstantEnum.MORE50.getMsg()); } <i style="color:transparent">来源gaodai$ma#com搞$代*码*网</i>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; } }

这样就实现了全局的统一异常处理,非常方便且优雅,快快在你的项目中用起来吧!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是SpringBoot使用统一异常处理详解的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot使用统一异常处理详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址