2026.6.18

SpringBoot统一返回结果封装和全局异常处理
核心知识

{
  "code": 200,    // 状态码:200成功,500服务异常
  "message": "提示信息", // 接口说明/异常文案
  "data": null    // 业务数据,成功时携带,异常时为null
}

具体步骤
1.创建Result类

package com.weitoutiao.common;

import lombok.Data;

@Data
public class Result<T> {
    // 状态码
    private Integer code;
    // 提示信息
    private String message;
    // 业务数据
    private T data;

    // 私有构造,禁止外部new,统一使用静态方法创建对象
    private Result(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    // 成功:携带数据
    public static <T> Result<T> success(T data) {
        return new Result<>(200, "success", data);
    }

    // 成功:仅返回提示文案,无数据
    public static <T> Result<T> success(String message) {
        return new Result<>(200, message, null);
    }

    // 失败:统一服务异常,code固定500
    public static <T> Result<T> error(String message) {
        return new Result<>(500, message, null);
    }
}

2.创建全局异常处理器

package com.weitoutiao.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 捕获所有运行时异常
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException e) {
        // 打印异常堆栈,方便后端定位bug
        e.printStackTrace();
        // 异常信息封装统一返回格式
        return Result.error(e.getMessage());
    }
}

3.修改HelloController使用Result

package com.weitoutiao.controller;

import com.weitoutiao.common.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public Result<String> hello() {
        return Result.success("微头条后端启动成功!");
    }
}
posted @ 2026-06-29 20:51  Daisy!  阅读(8)  评论(0)    收藏  举报