如何在SpringBoot中实现统一异常处理(springboot,编程语言)

时间:2024-05-01 18:13:20 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

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

@ControllerpublicclassHelloController{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(HelloController.class);@GetMapping(value="/hello")@ResponseBodypublicResulthello(){try{//TODO具体的逻辑省略……}catch(Exceptione){logger.error("hello接口异常={}",e);returnResultUtil.success(-1,"systemerror",null);}returnResultUtil.success(0,"success",null);}}

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

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

publicclassGlobalExceptionextendsRuntimeException{privateIntegercode;//因为我需要将异常信息也返回给接口中,所以添加code区分publicGlobalException(Integercode,Stringmessage){super(message);//把自定义的message传递个异常父类this.code=code;}publicIntegergetCode(){returncode;}publicvoidsetCode(Integercode){this.code=code;}}

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

@ControllerAdvicepublicclassExceptionHandle{@ResponseBody//因为我需要将抛出的异常返回给接口,所以加上此注解@ExceptionHandlerpublicResulthandle(Exceptione){if(einstanceofGlobalException){GlobalExceptionge=(GlobalException)e;returnResultUtil.success1(ge.getCode(),ge.getMessage());}returnResultUtil.success1(-1,"systemerror!");}}

写个测试类测试下

@GetMapping(value="/hello1")@ResponseBodypublicResulthello(@RequestParam(value="age",defaultValue="50",required=false)Integerage)throwsGlobalException{if(age<10){thrownewGlobalException(ConstantEnum.LESS10.getCode(),ConstantEnum.LESS10.getMsg());}elseif(age>50){thrownewGlobalException(ConstantEnum.MORE50.getCode(),ConstantEnum.MORE50.getMsg());}else{returnResultUtil.success1(0,"success");}}

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

publicenumConstantEnum{ERROR(-1,"systemerror!"),SUCCESS(100,"success"),LESS10(101,"自定义异常信息-我小于10岁"),MORE50(5001,"自定义异常信息-我大于50岁");privateIntegercode;privateStringmsg;publicIntegergetCode(){returncode;}publicStringgetMsg(){returnmsg;}ConstantEnum(Integercode,Stringmsg){this.code=code;this.msg=msg;}}

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

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:如何在SpringBoot中实现统一异常处理的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:SpringBoot中如何操作Redis下一篇:

12 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18