You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot控制器接口如何实现成功数据与错误信息等不同类型响应返回

实现方案

步骤1:定义通用统一响应结构(推荐,适配所有返回场景)

不管是正常返回业务对象、对象列表,还是异常返回错误信息,都使用统一结构,前后端对接更规范,无需兼容多种返回格式。

import lombok.Data;

// 泛型T支持任意类型的返回数据
@Data
public class ApiResponse<T> {
    // 响应状态码,可自定义业务码,也可以直接复用HTTP状态码
    private int code;
    // 提示信息,成功场景可返回操作描述,异常场景返回错误详情
    private String message;
    // 实际业务数据,正常场景存业务对象/列表,异常场景可设为null
    private T data;

    // 成功返回(仅带数据)
    public static <T> ApiResponse<T> success(T data) {
        ApiResponse<T> response = new ApiResponse<>();
        response.setCode(200);
        response.setMessage("操作成功");
        response.setData(data);
        return response;
    }

    // 成功返回(自定义状态码、提示、数据)
    public static <T> ApiResponse<T> success(int code, String message, T data) {
        ApiResponse<T> response = new ApiResponse<>();
        response.setCode(code);
        response.setMessage(message);
        response.setData(data);
        return response;
    }

    // 异常返回
    public static <T> ApiResponse<T> error(int code, String message) {
        ApiResponse<T> response = new ApiResponse<>();
        response.setCode(code);
        response.setMessage(message);
        response.setData(null);
        return response;
    }
}

如果你不想使用统一响应结构,也可以直接把ResponseEntity的泛型定义为<?>,正常时返回业务对象/列表,异常时返回自定义错误对象,但这种方式前端需要兼容多种返回结构,更推荐使用统一响应体方案。

步骤2:改造接口支持自定义错误和列表返回

改造原创建交易接口示例

@PostMapping("/transactions")
public ResponseEntity<ApiResponse<Transaction>> createTransaction(@RequestBody Transaction transaction) {
    try {
        User user = userRepository.findByUsername_(transaction.getUser().getUsername());
        Transaction _transaction = transactionRepository.save(new Transaction(transaction.getTransactionID(),user));
        // 正常返回业务对象,状态码用201符合REST规范
        return new ResponseEntity<>(ApiResponse.success(HttpStatus.CREATED.value(), "创建交易成功", _transaction), HttpStatus.CREATED);
    } catch (Exception e) {
        // 自定义返回错误信息,也可以根据异常类型返回更精准的提示
        return new ResponseEntity<>(ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "创建交易失败:" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

返回对象列表的接口示例

@GetMapping("/transactions")
public ResponseEntity<ApiResponse<List<Transaction>>> getTransactionList() {
    try {
        List<Transaction> transactions = transactionRepository.findAll();
        // 直接传入列表即可,泛型自动适配
        return new ResponseEntity<>(ApiResponse.success(transactions), HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "查询交易列表失败:" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

进阶优化:全局异常处理器(可选,代码更简洁)

如果不想每个接口都写try-catch,可以通过全局异常处理器统一拦截所有异常,接口只需处理正常业务逻辑:

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

@RestControllerAdvice
public class GlobalExceptionHandler {
    // 可单独处理自定义业务异常,返回不同的错误码和提示
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<Void>> handleGlobalException(Exception e) {
        return new ResponseEntity<>(ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统异常:" + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

改造后的接口无需写try-catch:

@PostMapping("/transactions")
public ResponseEntity<ApiResponse<Transaction>> createTransaction(@RequestBody Transaction transaction) {
    User user = userRepository.findByUsername_(transaction.getUser().getUsername());
    Transaction _transaction = transactionRepository.save(new Transaction(transaction.getTransactionID(),user));
    return new ResponseEntity<>(ApiResponse.success(HttpStatus.CREATED.value(), "创建交易成功", _transaction), HttpStatus.CREATED);
}

内容的提问来源于stack exchange,提问作者user16739552

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:27:03