SpringBoot结果封装和异常拦截的实现示例
作者:小虎哥的技术博客
在 SpringBoot 项目中,我们通常需要将结果数据封装成特定的格式,以方便客户端进行处理。我们可以将封装结果的代码封装成一个工具类或统一的响应类型,以简化代码的编写工作,并且方便统一管理。下面介绍一个简单的例子,说明如何对 SpringBoot 返回结果进行封装。
1. 定义 CommonResult 类
我们可以定义一个名为 CommonResult<T> 的类,用于封装接口的响应结果。它包含三个字段,分别对应了状态码 code、响应消息 msg 和响应数据 data,其中数据类型为泛型 T。code 字段是 int 类型的。
public class CommonResult<T> {
    private int code;  // 响应状态码
    private String msg;  // 响应消息
    private T data;  // 响应数据
    // 构造器
    public CommonResult() {}
    public CommonResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    // 省略 Getter 和 Setter 方法
}2. 定义响应码 ResponseCode
为了方便管理和调用响应状态码,我们可以定义一个名为 ResponseCode 的类,用来统一管理响应状态码。
public enum ResponseCode {
    SUCCESS(200, "操作成功"),
    FAIL(500, "操作失败");
    // 状态码和状态信息
    private final int code;
    private final String message;
    // 构造器
    private ResponseCode(int code, String message) {
        this.code = code;
        this.message = message;
    }
    // Getter 方法
    public int getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
}在这里我们只定义了两种响应状态码,分别是成功和失败,对应的状态码分别为 200 和 500。在实际项目中,我们可以根据实际业务场景定义更多的响应状态码。
3. 自定义异常 BizException
我们还可以定义一个自定义异常类 BizException,用于处理自定义异常场景,并在 GlobalExceptionHandler 中进行拦截与处理。
public class BizException extends RuntimeException {
    private int code;
    public BizException(ResponseCode responseCode) {
        super(responseCode.getMessage());
        this.code = responseCode.getCode();
    }
    // Getter 方法
    public int getCode() {
        return code;
    }
}Biz是英文Business的缩写,表示业务中发生的异常。
在该类中,我们定义了响应状态码对应的异常,并在构造方法中传入对应的 ResponseCode 来初始化异常的 code 字段。
4. 统一处理异常情况
在实际项目中,我们需要对异常情况进行处理,以保证系统的稳定性和可控性。因此,我们可以在对外暴露的 API 接口中添加异常处理机制,以统一处理系统抛出的异常情况,并防止系统挂掉。
在 SpringBoot 中,我们可以通过使用 @RestControllerAdvice 和 @ExceptionHandler 注解来进行异常处理。具体实现方式如下:
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public CommonResult<String> handleException(Exception e) {
        log.error("系统异常:{}", e.getMessage());
        return new CommonResult<>(ResponseCode.FAIL.getCode(), "系统错误,请联系管理员", null);
    }
    @ExceptionHandler(BizException.class)
    public CommonResult<String> handleBizException(BizException e) {
        log.error("业务异常:{}", e.getMessage());
        return new CommonResult<>(e.getCode(), e.getMessage(), null);
    }
}在上面的例子中,我们使用了 @RestControllerAdvice 注解来定义一个全局的异常处理类,使用 @ExceptionHandler(Exception.class) 和 @ExceptionHandler(BizException.class) 注解来分别处理全局异常和自定义的业务异常。
当系统发生异常时,会被 handleException 方法所捕获,输出异常日志,并返回一个业务失败的结果。而当业务异常发生时,会被 handleBizException 方法所捕获,返回该业务异常对应的状态码、响应消息和响应数据。
5. 使用结果封装类和模拟异常拦截
@RestController
@RequestMapping("/api")
public class UserController {
    // 省略注入代码
    @GetMapping("/users/{id}")
    public CommonResult<User> getUserById(@PathVariable("id") Long id) {
        User user = userService.getUserById(id);
        if (null != user) {
            return new CommonResult<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), user);
        } else {
            throw new BizException(ResponseCode.FAIL);
        }
    }
}使用CommonResult<User>来返回数据给前端
throw new BizException(ResponseCode.FAIL);抛出异常后会在异常拦截器那里拦截统一进行处理
6. 总结
在本篇教程中,我们介绍了如何使用 SpringBoot 来封装返回结果。我们定义了 CommonResult 类、ResponseCode 类和 BizException 自定义业务异常类,用于封装响应结果、统一管理响应状态码和处理自定义业务异常。我们也介绍了如何使用 @RestControllerAdvice 和 @ExceptionHandler 注解来统一处理异常情况,避免因为异常情况导致系统不稳定。在实际项目中,我们可以根据实际情况对以上代码进行修改和调整,以适应不同的业务场景。
到此这篇关于SpringBoot结果封装和异常拦截的实现示例的文章就介绍到这了,更多相关SpringBoot 结果封装和异常拦截内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
