一.返回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. git学习------>在CenterOS系统上安装GitLab并自定义域名访问GitLab管理页面

    目前就职的公司一直使用SVN作为版本管理,现在打算尝试从SVN迁移到Git.安排我来预言并搭建好相关的环境以及自己尝试使用Git.今天我就尝试在Center OS系统上安装GitLab,现在在此记录一 ...

  2. shell调用python脚本,并且向python脚本传递参数

    1.shell调用python脚本,并且向python脚本传递参数: shell中: python test.py $para1 $para2 python中: import sys def main ...

  3. 最简单的win7、win8免费升级正版win10图文教程

    https://www.microsoft.com/zh-cn/software-download/windows10 http://jingyan.baidu.com/article/19192ad ...

  4. Java集合—Map

    简介 Map用户保存具有映射关系的数据,因此Map集合里保存着两组数,一组值用户保存Map里的key,另一组值用户保存Map里的value,key和value都可以是任何引用类型的数据.Map的key ...

  5. FileZilla使用

    FileZilla是一个免费开源的FTP软件,分为客户端版本和服务器版本,具备所有的FTP软件功能.可控性.有条理的界面和管理多站点的简化方式使得Filezilla客户端版成为一个方便高效的FTP客户 ...

  6. 后缀自动机模板 SAM

    一点疑问: 当创建nq节点时,要不要把nq的cnt标记赋值为1? 讲道理nq节点也是代表一个子串啊,不过网上的模板都没赋值. 2017.9.18 update: 把memset部分重写,改成用节点用到 ...

  7. configparser模块来生成和修改配置文件

    1. 安装configparser模块 pip3 install configparser ##python2.7模块名为ConfigParser 2. 创建配置文件 import configpar ...

  8. IIS如何确定请求的处理程序

    1. 给定一个url请求,IIS需要确定它的文件名,扩展名,以及最相似的与本请求资源合适的"ScriptMaps"metadata (缓存的ISAPI扩展 - 应用程序扩展名映射列 ...

  9. ThinkPHP项目 公共方法存放位置

    ThinkPHP项目公共方法写在   根目录-> app-> common 里面 ThinkPHP模板公共方法卸载   根目录->app->模块名称->common  里 ...

  10. css 中 transition 需要注意的问题

    cubic-bezier 是 transition-timing-function 的值的一种. 四个参数的关系式如下(t 代表时间,取值范围 [0, 1]):P0(1-t)3 + 3P1t(1-t) ...