一.返回code数据的处理

代码:

Result.java
 /**
* http请求返回的最外层对象
* Created by 廖师兄
* 2017-01-21 13:34
*/
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 .java

public class ResultUtil {

    public static Result success(Object object) {
Result result = new Result();
result.setCode();
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(,bindingResult.getFieldError().getDefaultMessage());
} return ResultUtil.success(grilpepository.save(gril));
}

访问http://127.0.0.1:8081/grils

返回

{
"code": ,
"msg": "这个id必传",
"data": null
}

访问http://127.0.0.1:8081/grils/2

返回

  {
"id":
}

二:统一异常处理

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(-,"未知错误");
} }
}

使用:

@Service
public class GirlService {
public void getAge(Integer id) throws Exception{
Girl girl = girlRepository.findOne(id);
Integer age = girl.getAge();
if (age < ) {
//返回"你还在上小学吧" code=100
throw new GirlException(100,"你还在上小学吧");
}else if (age > && age < ) {
//返回"你可能在上初中" 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(-, "未知错误");
}
}
}

这个就是统一维护的文件,采用枚举

public enum ResultEnum {
UNKONW_ERROR(-, "未知错误"),
SUCCESS(, "成功"),
PRIMARY_SCHOOL(, "我猜你可能还在上小学"),
MIDDLE_SCHOOL(, "你可能在上初中"), ; 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 < ) {
//返回"你还在上小学吧" code=100
throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
}else if (age > && age < ) {
//返回"你可能在上初中" 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);
}

springboot统一异常处理及返回数据的处理的更多相关文章

  1. spring 或 springboot统一异常处理

    spring 或 springboot统一异常处理https://blog.csdn.net/xzmeasy/article/details/76150370 一,本文介绍spring MVC的自定义 ...

  2. SpringBoot 统一异常处理

    统一异常处理: @ControllerAdvice public class GlobalExceptionHandler { private Logger logger = LoggerFactor ...

  3. SpringBoot统一异常处理后TX-LCN分布式事务无法捕获异常进行回滚

    通常我们使用SpringBoot都会进行统一异常处理,例如写一个BaseController,在BaseController里进行统一异常处理,然后其他的Controller都继承BaseContro ...

  4. springboot统一异常处理类及注解参数为数组的写法

    统一异常处理类 package com.wdcloud.categoryserver.common.exception; import com.wdcloud.categoryserver.commo ...

  5. ASP.NET Core 统一异常处理和返回

    业务场景: 业务需求要求,需要对 ASP.NET Core 异常进行统一处理和返回,比如出现 500 错误和业务服务错误进行不同的处理和返回. 具体实现: using Microsoft.AspNet ...

  6. SpringBoot统一异常处理

    /** * 异常处理器 */ @RestControllerAdvice // public class BDExceptionHandler { private Logger logger = Lo ...

  7. Springboot统一异常处理(@ControllerAdvice)

    import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind ...

  8. spring boot 2 全局统一返回RESTful风格数据、统一异常处理

    全局统一返回RESTful风格数据,主要是实现ResponseBodyAdvice接口的方法,对返回值在输出之前进行修改.使用注解@RestControllerAdvice拦截异常并统一处理. 开发环 ...

  9. springboot返回统一接口与统一异常处理

    springboot返回统一接口与统一异常处理 编写人员:yls 编写时间:2019-9-19 0001-springboot返回统一接口与统一异常处理 简介 创建统一的返回格式 Result 封装统 ...

随机推荐

  1. 【我的Android进阶之旅】快速创建和根据不同的版本类型(Dev、Beta、Release)发布Android 开发库到Maven私服

    前言 由于项目越来越多,有很多公共的代码都可以抽取出一个开发库出来传到公司搭建好的Maven私服,以供大家使用. 之前搭建的Maven仓库只有Release和Snapshot两个仓库,最近由于开发库有 ...

  2. mysql总结思维导图

    mysql总结思维导图.脑图 先整理了一个思维导图出来,到时候再继续补充并且深入挖掘一下,再写博文. 另外,看了很多优秀的博文,在这里先mark一下. https://www.cnblogs.com/ ...

  3. 移植nand驱动补缺:make mrproper与make clean以及make distclean,find/grep. makefile

    make mrproper与make clean以及make distclean的区别: linux内核源码根目录下面的makefile中有很清晰的解析: useage: “clean”:Remove ...

  4. codeblocks opengl的配置

    codeblocks opengl的配置 GLUT 3.7 下载地址:http://www.opengl.org/resources/libraries/glut/glutdlls37beta.zip ...

  5. Delphi APP 開發入門(八)SQLite資料庫

    Delphi APP 開發入門(八)SQLite資料庫 分享: Share on facebookShare on twitterShare on google_plusone_share   閲讀次 ...

  6. android 22.3 环境

    http://developer.android.com/tools/sdk/eclipse-adt.html 要求 22.3https://dl.google.com/android/android ...

  7. Python 控制台进度条的实现

    进行爬虫等耗时的任务时,有时会想在控制台输出进度条,以显示当前任务进度.这里总结了两种方法. 方法1:使用tqdm模块 示例代码: from time import sleep from tqdm i ...

  8. Oracle Union Union All 对查询结果集操作

    在Oracle中提供了三种类型的集合操作: 并(UNION).交(INTERSECT).差(MINUS) Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序: Union Al ...

  9. 最好的 Xcode 自动生成版本号技术

    在 bloglovin ,我们使用自动生成版本号来设置Xcode,使当前的版本号为在Git活跃的分支上 的提交数.它一直正常工作着,但我们的技术也不是一帆风顺的. 糟糕的老方法 我们使用的技术是来自一 ...

  10. OpenStack之基础知识

    一.云计算 云计算(cloud computing)是基于互联网的相关服务的增加.使用和交付模式,通常涉及通过互联网来提供动态易扩展且经常是虚拟化的资源.云是网络.互联网的一种比喻说法.过去在图中往往 ...