SpringBoot进阶之使用异常替代返回错误码(拦截异常并统一处理)
来源:互联网 发布:gov.cn域名注册 编辑:程序博客网 时间:2024/06/15 07:20
直接上代码
1.Controller代码
@GetMapping(value = "/getage/{id}")public void getAge(@PathVariable("id") Integer id) throws Exception { girlService.getAge(id);}
2.Service代码
public void getAge(Integer id ) throws Exception { Girl girl =girlRepository.findOne(id); Integer age= girl.getAge(); if (age<18){ throw new TGException(ResultEnum.UNDER_AGE); } if (age>60){ throw new TGException(ResultEnum.OLDNESS); }}
3.TGException代码
public class TGException extends RuntimeException { private Integer code; public TGException(ResultEnum resultEnum){ super(resultEnum.getMessage()); this.code=resultEnum.getCode(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; }}4.ResultEnum 代码 (使用枚举 将返回的返回码和返回信息维护到同一个地方)
public enum ResultEnum { UNKONW_ERROR(-1,"未知错误"), SUCCESS(0,"成功"), UNDER_AGE(100,"未成年"), OLDNESS(101,"年龄超过60岁") ; private Integer code; private String message; ResultEnum(Integer code, String message) { this.code = code; this.message = message; } public Integer getCode() { return code; } public String getMessage() { return message; }}5.ExceptionHandle代码(异常处理)
@ControllerAdvicepublic class ExceptionHandle { private final static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class); @ResponseBody @ExceptionHandler(value = Exception.class) public Msg handle(Exception e){ if(e instanceof TGException){ TGException tgException=(TGException) e; return ResultUtil.error(tgException.getCode(),tgException.getMessage()); }else { logger.error("【系统异常】{}",e); return ResultUtil.error(-1, "未知错误"); } }}
附:相关注解说明
@ControllerAdvice spring3.2新增了@ControllerAdvice 注解,
可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,
并应用到所有@RequestMapping中(拦截异常并统一处理)
@ExceptionHandler(value = Exception.class) 异常处理器,此注解的作用是当出现其定义的异常时进行处理的方法
@ResponseBody 该注解用于读取Request请求的body部分数据,
使用系统默认配置的HttpMessageConverter进行解析,
然后把相应的数据绑定到要返回的对象上,
再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
阅读全文
0 0
- SpringBoot进阶之使用异常替代返回错误码(拦截异常并统一处理)
- SpringBoot进阶之统一异常处理(含源码)
- SpringBoot之统一异常处理
- Spring/SpringBoot定义统一异常错误码返回
- SpringBoot--统一异常处理
- SpringBoot-统一异常处理
- springboot统一异常处理
- SpringBoot统一异常处理
- SpringBoot 统一异常处理
- SpringBoot 统一异常处理
- springboot统一异常处理
- SpringBoot 统一异常处理--- @ControllerAdvice 使用
- 异常统一处理进阶
- Springboot-系统异常统一处理(接口编程异常处理)
- springboot统一异常处理机制
- SpringBoot(4) 统一异常处理
- spring boot之统一错误异常处理
- SpringBoot初始教程之统一异常处理(三)
- 【Anaconda】conda环境管理和包管理
- 【NOIP2017提高A组模拟10.10】Permutation
- LRecyclerView(RecyclerView)下拉刷新和上拉加载
- NKOJ 4191 Trie (状压dp)
- AngularJs的内置服务$window,$document,$location
- SpringBoot进阶之使用异常替代返回错误码(拦截异常并统一处理)
- 前端在线调试工具
- 对SEM的理解、账户层级结构、词的分类 sem做投放!(古志强网络营销师)
- 201709-1
- 引用专题讲座
- Java中String与int,char与int的互相转化
- Swift中导航栏的添加与一些属性
- 【JSON】读取json文件(一)
- enable_if 的一个奇怪用法