springboot统一异常处理及返回数据的处理
一.返回code数据的处理
代码:
Result.java
1 /** 2 * http请求返回的最外层对象 3 * Created by 廖师兄 4 * 2017-01-21 13:34 5 */ 6 public class Result<T> { 7 8 /** 错误码. */ 9 private Integer code; 10 11 /** 提示信息. */ 12 private String msg; 13 14 /** 具体的内容. */ 15 private T data; 16 17 public Integer getCode() { 18 return code; 19 } 20 21 public void setCode(Integer code) { 22 this.code = code; 23 } 24 25 public String getMsg() { 26 return msg; 27 } 28 29 public void setMsg(String msg) { 30 this.msg = msg; 31 } 32 33 public T getData() { 34 return data; 35 } 36 37 public void setData(T data) { 38 this.data = data; 39 } 40 }
ResultUtil .java
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; } }
@Entity public class Gril { @Id @GeneratedValue @NotNull(message = "这个id必传") private Integer id; public Integer getId(Integer id) { return this.id; } public void setId(Integer id) { this.id = id; } }
使用:
@RestController public class GrilController { //添加女生 @PostMapping(value = "/grils/{id}") public Result<Gril> grilAdd(@Valid Gril gril, BindingResult bindingResult){ if(bindingResult.hasErrors()) { //这个是把gril里面的这个id必传返回给前端 return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage()); } return ResultUtil.success(grilpepository.save(gril)); }
访问http://127.0.0.1:8081/grils
返回
{ "code": 1, "msg": "这个id必传", "data": null }
访问http://127.0.0.1:8081/grils/2
返回
{ "id": 21 }
二:统一异常处理
public class GrilException extends RuntimeException{ private Integer code; public GrilException(Integer code,String message) { super(message); this.code = code(); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
@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 GrilException){ GrilException grilException = (GrilException) e; return ResultUtil.error(grilException.getCode(),grilException.getMessage()); }else { //将系统异常以打印出来 logger.info("[系统异常]{}",e); return ResultUtil.error(-1,"未知错误"); } } }
使用:
@Service public class GirlService { public void getAge(Integer id) throws Exception{ Girl girl = girlRepository.findOne(id); Integer age = girl.getAge(); if (age < 10) { //返回"你还在上小学吧" code=100 throw new GirlException(100,"你还在上小学吧"); }else if (age > 10 && age < 16) { //返回"你可能在上初中" code=101 throw new GirlException(101,"你可能在上初中" ); } } }
@RestController public class GirlController { @Autowired private GirlService girlService; @GetMapping(value = "girls/getAge/{id}") public void getAge(@PathVariable("id") Integer id) throws Exception{ girlService.getAge(id); } }
执行结果为:
三:异常是统一维护:
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; } }
@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.error("【系统异常】{}", e); return ResultUtil.error(-1, "未知错误"); } } }
这个就是统一维护的文件,采用枚举
public enum ResultEnum { UNKONW_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 String getMsg() { return msg; } }
使用:
@Service public class GirlService { @Autowired private GirlRepository girlRepository; public void getAge(Integer id) throws Exception{ Girl girl = girlRepository.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岁,加钱 //... } }
@RestController public class GirlController { @Autowired private GirlService girlService; @GetMapping(value = "girls/getAge/{id}") public void getAge(@PathVariable("id") Integer id) throws Exception{ girlService.getAge(id); }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步