spring boot快速入门 8: 异常处理
Posted 刘晓明
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot快速入门 8: 异常处理相关的知识,希望对你有一定的参考价值。
异常处理简单样例:
第一步:创建result实体类
package com.payease.domain; /** * http请求返回的最外层对象 * Created by liuxiaoming on 2017/11/7. */ public class Result<T> { /** 错误码 */ private Integer code; /** 提示信息 */ private String msg; /** 具体内容 */ private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
第二步:创建resultUtil工具类
package com.payease.utils; import com.payease.domain.Result; /** * 对于结果集(Result)的工具类 * Created by liuxiaoming on 2017/11/7. */ public class ResultUtil { public static Result success(Object object){ Result result = new Result(); result.setCode(0); result.setMsg("成功"); result.setData(object); return result; } public static Result success(){ return success(null); } public static Result error(Integer code,String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; } }
第三步:在controller中调用
@Autowired private GirlRespository girlRespository; /** * 创建一个女生 */ @PostMapping("/girls") public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){ Result result = new Result(); if(bindingResult.hasErrors()){ return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage()); } girl.setCupSize(girl.getCupSize()); girl.setAge(girl.getAge()); return ResultUtil.success(girlRespository.save(girl)); }
第四步:启动项目 在postman中提交请求
请求成功:
请求失败:
样例:统一异常处理
第一步:创建枚举类ResultEnum(统一管理错误码和错误信息)
package com.payease.enums; /** * Created by liuxiaoming on 2017/11/7. */ public enum ResultEnum { UNKNOWN_ERROR(-1, "未知错误"), SUCCESS(0, "成功"), PRIMARY_SCHOOL(100,"你可能还在上小学"), MIDDLE_SCHOOL(101,"你可能在上初中"), ; private Integer code; private String msg; ResultEnum(Integer code, String msg){ this.code = code; this.msg = msg; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
第二步:创建自定义异常捕获类ExceptionHandle
package com.payease.handle; import com.payease.domain.Result; import com.payease.enums.ResultEnum; import com.payease.exception.GirlException; import com.payease.utils.ResultUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * 自定义异常捕获类 * Created by liuxiaoming on 2017/11/7. */ @ControllerAdvice public class ExceptionHandle { //日志 private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class) @ResponseBody public Result handle(Exception e){ if(e instanceof GirlException){ GirlException girlException = (GirlException)e; return ResultUtil.error(girlException.getCode(),girlException.getMessage()); }else{ logger.info("【系统异常】{}",e); return ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(),ResultEnum.UNKNOWN_ERROR.getMsg()); //return ResultUtil.error(-1,"未知错误:"); } } }
第三步:创建自定义异常类
package com.payease.exception; import com.payease.enums.ResultEnum; /** * 自定义异常 * Created by liuxiaoming on 2017/11/7. */ public class GirlException extends RuntimeException{ private Integer code; public GirlException(ResultEnum resultEnum) { super(resultEnum.getMsg()); this.code = resultEnum.getCode(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
第四步:在service中添加方法
public void getAge(Integer id) throws Exception{ Girl girl = girlRespository.findOne(id); Integer age = girl.getAge(); if(age < 10){ //返回 "你还在上小学吧" code=100 throw new GirlException(ResultEnum.PRIMARY_SCHOOL); }else if(age > 10 && age < 16){ //返回 "你可能在上初中" code=101 throw new GirlException(ResultEnum.MIDDLE_SCHOOL); } //如果>16岁,加钱 //... }
第五步:在controller中调用该方法
/** * 通过ID判断该女生年龄是否符合要求 * @param id * @throws Exception */ @GetMapping("girls/getAge/{id}") public void getAge(@PathVariable("id")Integer id) throws Exception{ girlService.getAge(id); }
第六步:启动项目 postman提交
以上是关于spring boot快速入门 8: 异常处理的主要内容,如果未能解决你的问题,请参考以下文章
Spring Cloud Spring Boot mybatis分布式微服务云架构快速入门
Spring Cloud Spring Boot mybatis分布式微服务云架构快速入门
Spring Cloud Spring Boot mybatis分布式微服务云架构快速入门