定义通用的返回对象

Posted by Kaka Blog on January 10, 2019

新建返回类

public class ResponseResult<T> {
    /**
     * success或者fail
     */
    private String status;
    private T data;

    private ResponseResult(String status, T data) {
        this.status = status;
        this.data = data;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Object getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    /**
     * 成功返回
     * @param data
     * @return
     */
    public static <T> ResponseResult create(T data) {
        return new ResponseResult("success", data);
    }

    public static ResponseResult create(CommonError data) {
        Map<String, Object> error = new HashMap<>(2);
        error.put("code", data.getErrCode());
        error.put("msg", data.getErrMsg());
        ResponseResult result = new ResponseResult("fail", error);
        return result;
    }
}

新建错误接口

public interface CommonError {
    int getErrCode();
    String getErrMsg();
    CommonError setErrMsg(String errMsg);
}

定义错误结果

public enum ErrorEnum implements CommonError {
    // 1开头的通用错误
    UNKNOW_ERROR(100001, "未知错误"),
    // 2开头为用户信息相关错误
    USER_NOT_EXIST(200001, "用户不存在"),
    ;
    private int code;
    private String msg;

    private ErrorEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    @Override
    public int getErrCode() {
        return this.code;
    }

    @Override
    public String getErrMsg() {
        return this.msg;
    }

    @Override
    public CommonError setErrMsg(String errMsg) {
        this.msg = errMsg;
        return this;
    }
}

定义业务错误异常

public class BusinessException extends Exception implements CommonError {
    private CommonError commonError;

    public BusinessException(CommonError commonError) {
        super();
        this.commonError = commonError;
    }

    public BusinessException(CommonError commonError, String errMsg) {
        super();
        this.commonError = commonError;
        this.commonError.setErrMsg(errMsg);
    }

    @Override
    public int getErrCode() {
        return this.commonError.getErrCode();
    }

    @Override
    public String getErrMsg() {
        return this.commonError.getErrMsg();
    }

    @Override
    public CommonError setErrMsg(String errMsg) {
        return this.commonError.setErrMsg(errMsg);
    }
}

定义全局异常处理

@RestControllerAdvice
public class ExceptionController {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseResult handleException(HttpServletRequest request, Throwable ex) {
        if (ex instanceof BusinessException) {
            return ResponseResult.create((BusinessException)ex);
        }
        else {
            return ResponseResult.create(ErrorEnum.UNKNOW_ERROR.setErrMsg(ex.getMessage()));
        }
    }
}

处理404错误:

# 出现错误时, 直接抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
# 不要为我们工程中的资源文件建立映射
spring.resources.add-mappings=false

测试

测试类

public class TestVO {
    private String name;
    private int age;
    private byte sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public byte getSex() {
        return sex;
    }

    public void setSex(byte sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "TestVO{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                '}';
    }
}

新建控制器

@RestController
public class TestController {
    @GetMapping("/test")
    public TestVO test() {
        TestVO testVO = new TestVO();
        testVO.setName("战神");
        testVO.setAge(23);
        testVO.setSex((byte)1);
        return testVO;
    }

    @GetMapping("/test2")
    public ResponseResult test2() {
        TestVO testVO = test();
        return ResponseResult.create(testVO);
    }

    @GetMapping("/test3")
    public ResponseResult test3() throws Exception {
        TestVO testVO = null;
        if (testVO == null) {
            throw new BusinessException(ErrorEnum.USER_NOT_EXIST);
        }
        return ResponseResult.create(testVO);
    }
}
  • 输入http://localhost:8080/test2,返回
    {
      "status": "success",
      "data": {
          "name": "战神",
          "age": 23,
          "sex": 1
      }
    }
    
  • 输入http://localhost:8080/test1,返回
    {
      "status": "fail",
      "data": {
          "msg": "No handler found for GET /test1",
          "code": 100001
      }
    }
    
  • 输入http://localhost:8080/test3,返回
    {
      "status": "fail",
      "data": {
          "msg": "用户不存在",
          "code": 200001
      }
    }
    

总结

定义通用的返回对象,包括返回正确信息,错误信息,以及异常处理。 正确信息使用泛型,不使用Object类型,便于接口说明文档生成时有对应的字段描述;错误信息允许自定义错误内容。