统一结果封装 & 全局异常处理
统一结果封装 & 全局异常处理
一、核心知识点
- 统一返回格式:
{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); } }2. 创建全局异常处理器:
- 右键
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()); } }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. 本次的工程目录:

四、使用Postman验证
1. 找到启动类,先启动主程序,点击运行按钮

2. 安装好Postman
3. 打开,新建一个Collection

4. 再添加一个Request

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

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

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


浙公网安备 33010602011771号