前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Springboot封装统一返回结果及全局异常处理

Springboot封装统一返回结果及全局异常处理

作者头像
超级小的大杯柠檬水
发布2024-11-21 12:40:56
发布2024-11-21 12:40:56
8800
代码可运行
举报
文章被收录于专栏:CYCY
运行总次数:0
代码可运行

Springboot 3封装统一返回结果+全局异常处理

自定义常用结果枚举类

创建HttpCodeEnum.java文件

代码语言:javascript
代码运行次数:0
复制
package com.example.test01.utils;
import lombok.Getter;

@Getter
public enum HttpCodeEnum {
    //==================== 登录相关枚举 ======================
    /**
     * 登陆超时
     */
    RC100(100, "登陆超时!"),

    /**
     * 用户未登录
     */
    RC101(101, "用户未登录,请先进行登录!"),

    /**
     * 账户被禁用,请联系管理员解决
     */
    RC102(102, "账户被禁用,请联系管理员解决!"),

    /**
     * 用户信息加载失败
     */
    RC103(103, "用户信息加载失败!"),

    /**
     * 用户身份信息获取失败
     */
    RC104(104, "用户身份信息获取失败!"),

    /**
     * 用户名不能为空
     */
    RC105(105, "用户名不能为空!"),

    /**
     * 密码不能为空
     */
    RC106(106, "密码不能为空!"),

    /**
     * 用户名或密码错误
     */
    RC107(107, "用户名或密码错误!"),

    /**
     * 用户登录成功
     */
    RC108(108, "用户登录成功!"),

    /**
     * 用户注销成功
     */
    RC109(109, "用户注销成功!"),

    //==================== 注册相关枚举 ======================

    /**
     * 验证码错误
     */
    RC300(300, "验证码错误!"),

    /**
     * 验证码过期
     */
    RC301(301, "验证码已过期!"),

    /**
     * 用户名已存在
     */
    RC302(302, "用户名已存在!"),

    //======================= 其他枚举 ==============================

    /**
     * 参数格式不合法
     */
    RC400(400, "参数格式不合法,请检查后重试!"),

    /**
     * 没有权限
     */
    RC403(403, "您没有操作权限!"),

    /**
     * 页面不存在
     */
    RC404(404, "未找到您请求的资源!"),

    /**
     * 请求方式错误
     */
    RC405(405, "请求方式错误,请检查后重试!"),

    /**
     * 超过最大上传大小
     */
    RC413(413, "超过最大上传大小!"),

    /**
     * 操作成功
     */
    SUCCESS(200, "操作成功!"),

    /**
     * 操作失败
     */
    ERROR(500, "操作失败!"),

    /**
     * 未知异常
     */
    RC600(600, "服务器繁忙或服务器错误,请稍后再试!");


    // 响应状态码
    private final Integer code;

    // 响应返回信息
    private final String message;

    HttpCodeEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

自定义统一返回格式

创建Response.java文件

代码语言:javascript
代码运行次数:0
复制
package com.example.test01.utils;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

/**
 * <p>
 * 统一结果集处理类
 * </p>
 *
 * @author CY
 * @email 1871263099@qq.com
 * @since 2024-09-28
 */
@Data
public class Response <T>{
    private static final int DEFAULT_FAIL_CODE = 500; // 定义默认失败状态码
    private static final String DEFAULT_FAIL_MSG = "fail"; // 定义默认失败信息

    @Schema(description = "数据")
    private T data=null;

    @Schema(description = "状态信息")
    private boolean state=true;

    @Schema(description = "返回信息")
    private String msg= "success";

    @Schema(description = "状态码")
    private int code=0;


    private Response<T> set(T data, String msg, int code, boolean state) {
        this.data = data;
        this.msg = msg;
        this.code = code;
        this.state = state;
        return this;
    }

    public static <K> Response<K> newSuccess(K data) {
        return new Response<K>().set(data, "success", 0, true);
    }

    public static <K> Response<K> newSuccess(K data, String msg) {
        return new Response<K>().set(data, msg, 0, true);
    }

    public static <K> Response<K> newSuccess(K data, String msg, int code) {
        return new Response<K>().set(data, msg, code, true);
    }

    public static <K> Response<K> newFail() {
        return new Response<K>().set(null, DEFAULT_FAIL_MSG, DEFAULT_FAIL_CODE, false);
    }

    public static <K> Response<K> newFail(String msg) {
        return new Response<K>().set(null, msg, DEFAULT_FAIL_CODE, false);
    }

    public static <K> Response<K> newFail(String msg, int code) {
        return new Response<K>().set(null, msg, code, false);
    }

    /**
     * 设置 状态码 和 信息
     *
     * @param httpCodeEnum 枚举信息
     * @return JsonResult
     */
    public static <K> Response<K> codeAndMessage(HttpCodeEnum httpCodeEnum) {
        return new Response<K>().set(null, httpCodeEnum.getMessage(), httpCodeEnum.getCode(), false);
    }
}

自定义业务异常处理

很多时候我们在处理业务逻辑的时候需要抛出一些自定义的异常 创建BusinessException.java文件

代码语言:javascript
代码运行次数:0
复制
package com.example.test01.utils;
import lombok.Getter;

/**
 * 业务异常处理类
 */
@Getter
public class BusinessException extends RuntimeException {

    /**
     * 状态码
     */
    private final Integer code;

    /**
     * 报错信息
     */
    private final String message;

    /**
     * 全参构造方法
     */
    public BusinessException(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 构造方法
     */
    public BusinessException(String message) {
        this(HttpCodeEnum.ERROR.getCode(), message);
    }

    /**
     * 构造方法
     */
    public BusinessException(HttpCodeEnum httpCodeEnum) {
        this(httpCodeEnum.getCode(), httpCodeEnum.getMessage());
    }
}

自定义全局异常处理

创建GlobalException.java文件

代码语言:javascript
代码运行次数:0
复制
package com.example.test01.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常信息处理类
 */
//@Slf4j
@RestControllerAdvice
public class GlobalException {


    /**
    * @Description 处理业务异常
    * @return Response
    * @Author CY
    * @Date 2024/9/21
    */
    @ExceptionHandler(value = BusinessException.class)
    public Response businessException(BusinessException e) {
        System.out.println(e.getMessage());
        return Response.newFail(e.getMessage(),e.getCode());
    }

    /**
    * @Description  处理未知(600)异常
    * @Author CY
    * @Date 2024/9/21
    */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response globalException(Exception e) {
        System.out.println("服务器错误:"+e.getMessage());
        e.printStackTrace();
        return Response.codeAndMessage(HttpCodeEnum.RC600);
    }

    /**
    * @Description 404错误
    * @Author CY
    * @Date 2024/9/21
    */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Response noHandlerFoundException(HttpServletRequest e) {
        return Response.codeAndMessage(HttpCodeEnum.RC404);
    }


    /**
    * @Description 超过最大上传文件大小错误(413)
    * @Author CY
    * @Date 2024/9/21
    */
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    @ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
    public Response maxUploadSizeExceededException(HttpServletRequest e) {
        return Response.codeAndMessage(HttpCodeEnum.RC413);
    }

    /**
     * @Description 请求方式错误(405)
     * @Author CY
     * @Date 2024/9/21
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Response httpRequestMethodNotSupportedException(HttpServletRequest e) {
        return Response.codeAndMessage(HttpCodeEnum.RC405);
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-09-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Springboot 3封装统一返回结果+全局异常处理
    • 自定义常用结果枚举类
    • 自定义统一返回格式
    • 自定义业务异常处理
    • 自定义全局异常处理
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档