统一结果封装 & 全局异常处理

一、教学目标
创建Result类统一API返回格式。
使用@ControllerAdvice处理全局异常。
二、核心知识点(简要)
统一返回格式:{code, message, data},便于前端处理。
@RestControllerAdvice:全局异常处理器。
@ExceptionHandler:指定处理的异常类型。
三、操作步骤
在上次课的基础上操作

  1. 创建Result类:
    右键com.weitoutiao文件夹,新建java类:common.Result
    类中内容:
package com.weitoutiao.common;

import lombok.Data;

@Data
public class Result<T> {
    private Integer code;
    private String message;
    private T data;

    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);
    }
    public static <T> Result<T> error(String message) {
        return new Result<>(500, message, null);
    }
}
  1. 创建全局异常处理器:
    右键common文件夹,新建java类:GlobalExceptionHandler
    类中内容:
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) {
        e.printStackTrace();
        return Result.error(e.getMessage());
    }
}
  1. 修改HelloController使用Result:
    HelloController的内容如下:
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("微头条后端启动成功!");
    }
}
  1. 本次课的工程目录:
    四、使用Postman验证
  2. 找到启动类,先启动主程序,点击运行按钮
  3. 安装好Postman
  4. 打开,新建一个Collection
  5. 再添加一个Request
  6. Request名就叫hello,然后保存
  7. 在URL里输入:http://localhost:8080/hello
  8. 点击发送Send,在Body里会显示出后端返回的数据,选JSON格式
posted on 2026-06-24 10:37  爱我的果果吖  阅读(17)  评论(0)    收藏  举报