首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Boot 自定義 HTTP 響應狀態碼實戰:ResponseEntity 最佳實踐

     編輯:Java 相關知識

業務背景

微服務間 HTTP 調用,傳統做法在 JSON 體中包裹 status 字段判斷成敗,違背 RESTful 語義。標準 HTTP 狀態碼(200/400/401/404/500...)才是正規溝通協議。

三種實現方式對比

方式一:@ResponseStatus 註解(不推薦)

@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "server error")
public class ServerException extends RuntimeException {}

@GetMapping("/user")
public String getUser(@RequestParam String name) {
    if (StringUtils.isEmpty(name)) throw new ServerException();
    return "zhangsan";
}

缺點:狀態碼寫死、reason 無法動態、異常類爆炸、無法返回業務數據體。

方式二:HttpServletResponse 原生 API(繁瑣)

@GetMapping("/user")
public void getUser(HttpServletResponse response) throws IOException {
    response.setStatus(500);
    response.setContentType("application/json;charset=UTF-8");
    response.getWriter().write("{\"error\":\"server error\"}");
}

缺點:方法必須 void、失去 @ResponseBody 自動序列化、樣板代碼多、易忘編碼設置。

方式三:ResponseEntity(推薦 ✅)

@GetMapping("/user")
public ResponseEntity<Map<String, Object>> getUser(@RequestParam String name) {
    Map<String, Object> body = new HashMap<>();
    if (StringUtils.isEmpty(name)) {
        body.put("error", "name is required");
        return ResponseEntity.badRequest().body(body); // 400
    }
    body.put("name", "zhangsan");
    return ResponseEntity.ok(body); // 200
}

// 更多靜態工廠方法
ResponseEntity.created(location).header("X-Custom", "val").body(obj); // 201
ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);               // 403
ResponseEntity.noContent().build();                                    // 204

ResponseEntity 核心優勢

  • 三元組:body + status + headers 完整控制
  • 類型安全:泛型 ResponseEntity<T>,配合 @ResponseBody 自動 Jackson 序列化
  • 流式構建:ResponseEntity.ok().header(...).body(...) 鏈式調用
  • RestTemplate 協作:restTemplate.getForEntity(uri, String.class) 直接獲取狀態碼與體

統一異常處理中返回 ResponseEntity

@RestControllerAdvice
public class GlobalHandler {
    @ExceptionHandler(BizException.class)
    public ResponseEntity<ErrorResponse> handleBiz(BizException e) {
        HttpStatus status = switch (e.getErrorCode()) {
            case "AUTH_001" -> HttpStatus.UNAUTHORIZED;
            case "PERM_002" -> HttpStatus.FORBIDDEN;
            case "RES_003"  -> HttpStatus.NOT_FOUND;
            default         -> HttpStatus.BAD_REQUEST;
        };
        return ResponseEntity.status(status)
            .body(new ErrorResponse(e.getErrorCode(), e.getMessage()));
    }
}

常用狀態碼速查

碼含義典型場景
200OK成功返回數據
201CreatedPOST 創建資源,返回 Location 頭
204No ContentDELETE/UPDATE 成功無返回體
400Bad Request參數校驗失敗
401UnauthorizedToken 失效/缺失
403Forbidden權限不足
404Not Found資源不存在
409Conflict資源衝突(如唯一鍵重複)
500Internal Server Error未捕獲異常

最佳實踐總結

  1. Controller 返回 ResponseEntity<T> 而非直接 T
  2. 業務異常映射具體 4xx 碼,系統異常統一 500
  3. 錯誤響應體統一結構:{code, message, timestamp, path}
  4. 集成 OpenAPI/Swagger 自動生成文檔
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved