1 Star 0 Fork 0

createsmile / result_study

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

springboot封装返回结果,全局异常处理

引入依赖

<!-- springboot启动类 -->
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 自动get/set的包插件 -->
<dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
</dependency>

统一返回主类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    private int code;
    private String msg;
    private T data;

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

    public Result(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
    }
}

返回状态码信息

public enum ResultCode {
    /* 成功状态码 */
    SUCCESS(1, "操作成功!"),

    /* 错误状态码 */
    FAIL(-1, "操作失败!"),

    /* 参数错误:10001-19999 */
    PARAM_MISSING(10001, "请求参数缺失"),

    /* 用户错误:20001-29999*/
    USER_NOT_LOGGED_IN(20001, "用户未登录,请先登录"),
    /* 业务错误:30001-39999*/
    CASE_NOT_EXIST(30001, "案例不存在"),
    /* 系统错误:40001-49999 */
    SYSTEM_INNER_ERROR(40001, "系统繁忙,请稍后重试"),
    SYSTEM_SEND_EMAIL_ERROR(40002, "邮箱发送错误"),
    /* 权限错误:70001-79999 */
    PERMISSION_TOKEN_INVALID(70001, "无效token"),
    PERMISSION_FORBIDDEN(70002, "无权利操作");

    /**
     * 操作代码
     */
    int code;
    /**
     * 提示信息
     */
    String msg;

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

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

快捷返回工具类

public class ResultUtil {
    /**
     * 操作成功,只返回结果码和提示信息
     */
    public static Result success() {
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 操作成功,只返回结果码和具体的数据,但不返回提示信息
     */
    public static Result success(int code, String msg) {
        return new Result(code, msg);
    }

    /**
     * 操作成功,返回具体的数据、结果码和提示信息
     */
    public static Result success(Object data) {
        Result<Object> result = new Result(ResultCode.SUCCESS);
        result.setData(data);
        return result;
    }

    /**
     * 操作成功,返回具体的数据、结果码和提示信息
     */
    public static Result success(Integer code, String msg, Object data) {
        return new Result<>(code,msg,data);
    }

    /**
     * 操作成功,只返回结果码和提示信息
     */
    public static Result fail() {
        return new Result(ResultCode.FAIL);
    }

    /**
     * 操作失败,只返回指定的结果码和具体的数据,但不返回提示信息
     */
    public static Result fail(int code, String msg) {
        return new Result(code, msg);
    }

    /**
     * 操作失败,返回具体的数据、结果码和提示信息
     */
    public static Result fail(Object data) {
        Result<Object> result = new Result(ResultCode.FAIL);
        result.setData(data);
        return result;
    }

    /**
     * 操作失败,返回具体的数据、结果码和提示信息
     */
    public static Result fail(Integer code, String msg, Object data) {
        return new Result<>(code,msg,data);
    }
}

自定义异常信息

public class CustomException extends RuntimeException {

    /**
     * 错误枚举代码
     */
    private ResultCode resultCode;

    public CustomException(ResultCode resultCode){
        super(resultCode.getMsg());
        this.resultCode = resultCode;
    }

    public CustomException(ResultCode resultCode, Object... args){
        super(resultCode.getMsg());
        String message = MessageFormat.format(resultCode.getMsg(), args);
        resultCode.setMsg(message);
        this.resultCode = resultCode;
    }

    public ResultCode getResultCode(){
        return resultCode;
    }

}

全局异常处理

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(CustomException.class)
    public Object handleException(CustomException e) {
        // 打印异常信息
        log.error("### 异常信息:{} ###", e.getMessage());
        return new Result(e.getResultCode());
    }

    /**
     * 参数校验统一异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        Result<Object> result = new Result(ResultCode.PARAM_MISSING);
        if (fieldError != null) {
            result.setMsg(fieldError.getDefaultMessage());
        }
        return result;
    }
    /**
     * 处理所有不可知的异常
     */
    @ExceptionHandler(Exception.class)
    public Object handleOtherException(Exception e) {
        //打印异常堆栈信息
        e.printStackTrace();
        // 打印异常信息
        log.error("### 不可知的异常:{} ###", e.getMessage());
        return new Result(ResultCode.SYSTEM_INNER_ERROR);
    }
}

使用演示

@RestController
public class TestController {
    @GetMapping("test1")
    public Object test1() {
        return ResultUtil.success("测试结果成功");
    }

    @GetMapping("test2")
    public Object test2(Integer id) {
        //如果id为0或者null就会全局异常
        if ((10 / id) % 2 == 0) {
            return ResultUtil.success("结果是偶数!!!");
        } else {
            throw new CustomException(ResultCode.PERMISSION_FORBIDDEN);
        }
    }
}

空文件

简介

springboot返回结果封装,全局异常处理 展开 收起
Java
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/createsmile/result_study.git
git@gitee.com:createsmile/result_study.git
createsmile
result_study
result_study
master

搜索帮助