整合框架(spring...) 统一异常处理

1、 我们想让异常结果也显示为统一的返回结果对象,并且统一处理系统的异常信息,那么需要统一异常处理。

++附加:创建封装错误状态码和错误消息VO++

代码如下:

Result

复制代码
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@Data
@Schema(description = "响应结果实体类")
public class Result<T> {


    //返回码
    @Schema(description = "业务状态码")
    private Integer code;

    //返回消息
    @Schema(description = "响应消息")
    private String message;

    //返回数据
    @Schema(description = "业务数据")
    private T data;


    // 私有化构造
    private Result() {}

    // 返回数据
    public static <T> Result<T> build(T body, Integer code, String message) {
        Result<T> result = new Result<>();
        result.setData(body);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    // 通过枚举构造Result对象
    public static <T> Result build(T body , ResultCodeEnum resultCodeEnum) {
        return build(body , resultCodeEnum.getCode() , resultCodeEnum.getMessage()) ;
    }

}
复制代码
ResultCodeEnum
复制代码
import lombok.Getter;

@Getter // 提供获取属性值的getter方法
public enum ResultCodeEnum {

    SUCCESS(200 , "操作成功"),
    LOGIN_ERROR(201 , "用户名或者密码错误"),
    VALIDATECODE_ERROR(202 , "验证码错误") ,
    LOGIN_AUTH(208 , "用户未登录"),
    USER_NAME_IS_EXISTS(209 , "用户名已经存在"),
    SYSTEM_ERROR(9999 , "您的网络有问题请稍后重试"),
    NODE_ERROR( 217, "该节点下有子节点,不可以删除"),
    DATA_ERROR(204, "数据异常"),
    ACCOUNT_STOP( 216, "账号已停用"),
    STOCK_LESS( 219, "库存不足"),;

    private Integer code ;      // 业务状态码
    private String message ;    // 响应消息

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

}

异常类:

创建自定义异常类

复制代码
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import lombok.Data;
@SuppressWarnings("all")

@Data
public class NiuException extends RuntimeException{
    private String message; // 错误消息
    private Integer code;   // 错误状态码
    private ResultCodeEnum resultCodeEnum;    // 封装错误状态码和错误消息
    publicNiuException(ResultCodeEnum resultCodeEnum){
        this.resultCodeEnum=resultCodeEnum;
        this.code= resultCodeEnum.getCode();
        this.message=resultCodeEnum.getMessage();
    }
    public NiuException(String message,Integer code){
        this.code=code;
        this.message=message;
    }

}

全局异常处理器

在common-service中创建统一异常处理类GlobalExceptionHandler

// 处理自定义异常在GlobalExceptionHandler类上加自定义注解:@ExceptionHandler(value = NiuException.class)

复制代码
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ControllerAdvice 给controller增加统一的操作处理
 * 相当于是controller的增强器
 */
@ControllerAdvice
public class GlobalExceptionHandler{
    /**
     * @ExceptionHandler(NiuException.class)出现异常的时候执行
     * @return
     * @ResponseBody 返回json格式
     */
     // 处理自定义异常
    @ExceptionHandler(NiuException.class) 
    @ResponseBody
    public Result error(NiuException e){
        return Result.build(null, e.getResultCodeEnum());
    }

}

创作不易,大家合作共赢

相关推荐
逝水无殇10 分钟前
C# 文件的输入与输出详解
开发语言·数据库·后端·c#
YIAN33 分钟前
从手写 Agent 工具到 MCP 协议:一文搞懂大模型跨进程跨语言工具调用
后端·agent·mcp
小兔崽子去哪了1 小时前
Docker 删除镜像后磁盘空间没有释放?
后端·docker·容器
凤凰院凶涛QAQ1 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
高明珠2 小时前
麒麟 V10 SP1 排查实录:ttyS5 每 10 秒莫名收到一批报文,元凶是 eGTouchD
后端
卷无止境2 小时前
Python FFI 技术深度解析:ctypes、cffi 与 pybind11 的性能差异与实践挑战
后端·python
ServBay2 小时前
AI Gateway 是什么?为什么每个平台都在做
后端·aigc·ai编程
SamDeepThinking2 小时前
Vibe Coding最重要的是Spec
后端·程序员·ai编程
掘金_答案2 小时前
上线那天,一个 ConcurrentHashMap 差点送走我的 AI 客服——3 天排查 JVM 血泪史
java·后端·架构
妙码生花2 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(三十三):权限规则管理器
后端·go·gin