ApiErrorResponse.java
Springboot/bookstore-api/src/main/java/com/example/bookstore/dto/ApiErrorResponse.java
package com.example.bookstore.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.http.HttpStatus;
import java.time.LocalDateTime;
import java.util.Map;
/**
* 統一的「錯誤回應」格式。
*
* 【為什麼需要統一格式?】
* 讓所有錯誤(404、400、401、403、409、500...)都長得一樣,
* 前端只要寫一次錯誤處理邏輯,開發與除錯都更輕鬆。
*
* 回應範例(驗證失敗 400):
* {
* "timestamp": "2026-08-14T10:30:00",
* "status": 400,
* "error": "Bad Request",
* "message": "輸入資料驗證失敗",
* "path": "/api/books",
* "fieldErrors": { "title": "書名不可為空白", "price": "價格不可為負數" }
* }
*
* @JsonInclude(NON_NULL):值為 null 的欄位不輸出到 JSON
* (例如一般錯誤沒有 fieldErrors,就不會出現這個欄位)。
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public record ApiErrorResponse(
LocalDateTime timestamp, // 錯誤發生時間
int status, // HTTP 狀態碼數字(如 404)
String error, // 狀態碼名稱(如 "Not Found")
String message, // 給人看的錯誤說明
String path, // 發生錯誤的 API 路徑
Map<String, String> fieldErrors // 欄位驗證錯誤明細(僅 400 使用)
) {
/** 建立一般錯誤回應(不含欄位錯誤明細) */
public static ApiErrorResponse of(HttpStatus status, String message, String path) {
return new ApiErrorResponse(
LocalDateTime.now(), status.value(), status.getReasonPhrase(),
message, path, null);
}
/** 建立含「欄位錯誤明細」的回應(驗證失敗 400 專用) */
public static ApiErrorResponse of(HttpStatus status, String message, String path,
Map<String, String> fieldErrors) {
return new ApiErrorResponse(
LocalDateTime.now(), status.value(), status.getReasonPhrase(),
message, path, fieldErrors);
}
}
相关文章
BookstoreApiApplication.java
BookstoreApiApplication.java — java source code from the Springboot learning materials (Springboot/bookstore-api/src/main/java/com/example/bookstore/BookstoreApiApplication.java).
阅读文章 →DataInitializer.java
DataInitializer.java — java source code from the Springboot learning materials (Springboot/bookstore-api/src/main/java/com/example/bookstore/config/DataInitializer.java).
阅读文章 →SecurityConfig.java
SecurityConfig.java — java source code from the Springboot learning materials (Springboot/bookstore-api/src/main/java/com/example/bookstore/config/SecurityConfig.java).
阅读文章 →AuthController.java
AuthController.java — java source code from the Springboot learning materials (Springboot/bookstore-api/src/main/java/com/example/bookstore/controller/AuthController.java).
阅读文章 →BookController.java
BookController.java — java source code from the Springboot learning materials (Springboot/bookstore-api/src/main/java/com/example/bookstore/controller/BookController.java).
阅读文章 →AuthResponse.java
AuthResponse.java — java source code from the Springboot learning materials (Springboot/bookstore-api/src/main/java/com/example/bookstore/dto/AuthResponse.java).
阅读文章 →