如何在SpringBoot中实现统一异常处理
导读:本文共1601.5字符,通常情况下阅读需要5分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 场景:针对异常处理,我们原来的做法是一般在最外层捕获异常即可,例如在Controller中@ControllerpublicclassHelloController{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(HelloController.class);@GetMapping(valu... ...
音频解说
目录
(为您整理了一些要点),点击可以直达。场景:针对异常处理,我们原来的做法是一般在最外层捕获异常即可,例如在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;}}
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:
如何在SpringBoot中实现统一异常处理的详细内容,希望对您有所帮助,信息来源于网络。