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

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

一、核心知识点

  • 统一返回格式{code, message, data},便于前端处理。
  • @RestControllerAdvice:全局异常处理器。
  • @ExceptionHandler:指定处理的异常类型。

二、操作步骤

1. 创建Result

  • 右键com.weitoutiao文件夹,新建java类:common.Result

3203083-20260616221335588-1729091322

  • 类中内容:

    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);
        }
    }
    

2. 创建全局异常处理器

  • 右键common文件夹,新建java类:GlobalExceptionHandler

3203083-20260616221354887-2044267937

  • 类中内容:

    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());
        }
    }
    

3. 修改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("微头条后端启动成功!");
        }
    }
    

4. 本次的工程目录:

3203083-20260616221413897-509868316

四、使用Postman验证

1. 找到启动类,先启动主程序,点击运行按钮

3203083-20260616221424205-1748637583

2. 安装好Postman

3. 打开,新建一个Collection

3203083-20260616221436246-1829732159

4. 再添加一个Request

3203083-20260616221449684-1398919076

5. Request名就叫hello,然后保存

3203083-20260616221456898-470060473

6. 在URL里输入:http://localhost:8080/hello

3203083-20260616221505633-1743208474

7. 点击发送Send,在Body里会显示出后端返回的数据,选JSON格式,如下:

3203083-20260616221511969-1568978537

posted @ 2026-06-26 21:25  沈瑜九  阅读(5)  评论(0)    收藏  举报