springboot + 统一返回json数据 + 统一异常处理

环境

1、创建一个springboot项目

  • 只需引入web依赖即可

在这里插入图片描述

  • pom.xml文件
<dependencies>
     <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
</dependencies>

2、简单的配置

# 应用名称
spring.application.name=res_exc_demo
# 端口号
server.port=8099

统一返回

1、定义一个类,返回固定的格式

一般格式包括

  • 状态码
  • 状态码信息
  • 具体返回数据
public class Resp<T> {
    
    

    //状态码
    private int code = 200;
    //状态码信息
    private String msg = "success";
    //返回的信息
    private T data;

    private Resp(int code,String msg,T data){
    
    
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Resp success(T data){
    
    
        Resp resp = new Resp(200, "success", data);
        return resp;
    }

    public static <T> Resp success(String msg,T data){
    
    
        Resp resp = new Resp(200,msg, data);
        return resp;
    }

    public static <T> Resp error(AppExceptionCodeMsg appExceptionCodeMsg){
    
    
        Resp resp = new Resp(appExceptionCodeMsg.getCode(), appExceptionCodeMsg.getMsg(), null);
        return resp;
    }
    public static <T> Resp error(int code,String msg){
    
    
        Resp resp = new Resp(code,msg, null);
        return resp;
    }

    public int getCode() {
    
    
        return code;
    }

    public String getMsg() {
    
    
        return msg;
    }

    public T getData() {
    
    
        return data;
    }

}

2、controller统一返回

@RestController
public class DemoController {
    
    

    @GetMapping("demo")
    public Resp<String> demo1(String name){
    
    
    	//...
       return Resp.success("default");
    }
}

统一异常处理

1、创建一个枚举类型

存储各种类型的异常状态码和信息

package com.pzz.exce;

/**
 * 枚举类,所有自定义异常的状态码和信息
 */
//这个枚举类中定义的都是跟业务有关的异常
public enum AppExceptionCodeMsg {
    
    

    INVALID_CODE(10000,"验证码无效"),
    USERNAME_NOT_EXISTS(10001,"用户名不存在"),
    USER_CREDIT_NOT_ENOUTH(10002,"用户积分不足");

    private int code ;
    private String msg ;

    public int getCode() {
    
    
        return code;
    }

    public String getMsg() {
    
    
        return msg;
    }


    AppExceptionCodeMsg(int code, String msg){
    
    
        this.code = code;
        this.msg = msg;
    }

}

2、创建自定义的异常类

package com.pzz.exce;

public class AppException extends RuntimeException{
    
    

    private int code = 500;
    private String msg = "服务器异常";


    public AppException(AppExceptionCodeMsg appExceptionCodeMsg){
    
    
        super();
        this.code = appExceptionCodeMsg.getCode();
        this.msg = appExceptionCodeMsg.getMsg();

    }

    public AppException(int code,String msg){
    
    
        super();
        this.code = code;
        this.msg = msg;

    }

    public int getCode() {
    
    
        return code;
    }

    public String getMsg() {
    
    
        return msg;
    }

}

3、创建全局统一异常处理类

package com.pzz.exce;

import com.pzz.resp.Resp;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    
    


    @ExceptionHandler(value = {
    
    Exception.class})
    @ResponseBody
    public <T> Resp<T> exceptionHandler(Exception e){
    
    
        //这里先判断拦截到的Exception是不是我们自定义的异常类型
        if(e instanceof AppException){
    
    
            AppException appException = (AppException)e;
            return Resp.error(appException.getCode(),appException.getMsg());
        }

        //如果拦截的异常不是我们自定义的异常(例如:数据库主键冲突)
        return Resp.error(500,"服务器端异常");
    }
}

4、controller

package com.pzz.controller;

import com.pzz.exce.AppException;
import com.pzz.exce.AppExceptionCodeMsg;
import com.pzz.resp.Resp;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
public class DemoController {
    
    


    @GetMapping("demo")
    public Resp<String> demo1(String name){
    
    

        if("ok".equals(name)){
    
    
            return Resp.success("succ");
        }
        if("err".equals(name)){
    
    
            //抛业务相关的异常
            throw new AppException(AppExceptionCodeMsg.USERNAME_NOT_EXISTS);
        }

        if("errcode".equals(name)){
    
    
            throw new AppException(AppExceptionCodeMsg.INVALID_CODE);
        }
        if("0".equals(name)){
    
    
            int i=1/0;
        }

        //检查用户积分是否足够,如果不够,就抛出异常
        if("notenough".equals(name)){
    
    
            throw new AppException(AppExceptionCodeMsg.USER_CREDIT_NOT_ENOUTH);
        }

        return Resp.success("default");
    }
    
   @GetMapping("list")
    public Resp<List> list(){
    
    
		List<String> list = Arrays.asList("zhangsan","lisi","wangwu");

        return Resp.success(list);
    }
}

测试效果

在这里插入图片描述
在这里插入图片描述

结束!
hy:6


									人可以犯错,但是不可犯同一个错。---苏格拉底

猜你喜欢

转载自blog.csdn.net/weixin_49107940/article/details/130924139