
Python實現動圖生成:輕松創建自定義表情包
private boolean success;
private String message;
private T data;
private List<String> errors;
private int errorCode;
private long timestamp; // Adding timestamp for tracking
private String path; // Adding path to identify the API endpoint
// Constructors, getters, and setters
}
boolean
2.消息 :
String
3.數據:
T
4.錯誤 :
List<String>
5. 錯誤代碼 :
int
6.時間戳 :
long
7.路徑 :
String
讓我們創建實用的方法來生成響應,以保持不重復。這樣做既可以確保一致性,又能減少樣板代碼。
public class ResponseUtil {
public static <T> ApiResponse<T> success(T data, String message, String path) {
ApiResponse<T> response = new ApiResponse<>();
response.setSuccess(true);
response.setMessage(message);
response.setData(data);
response.setErrors(null);
response.setErrorCode(0); // No error
response.setTimestamp(System.currentTimeMillis());
response.setPath(path);
return response;
}
public static <T> ApiResponse<T> error(List<String> errors, String message, int errorCode, String path) {
ApiResponse<T> response = new ApiResponse<>();
response.setSuccess(false);
response.setMessage(message);
response.setData(null);
response.setErrors(errors);
response.setErrorCode(errorCode);
response.setTimestamp(System.currentTimeMillis());
response.setPath(path);
return response;
}
public static <T> ApiResponse<T> error(String error, String message, int errorCode, String path) {
return error(Arrays.asList(error), message, errorCode, path);
}
}
我們可以使用 @ControllerAdvice 和 @ExceptionHandler 注解來全局處理異常,確保捕獲任何未處理的錯誤并以標準響應格式返回。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Void>> handleException(HttpServletRequest request, Exception ex) {
List<String> errors = Arrays.asList(ex.getMessage());
ApiResponse<Void> response = ResponseUtil.error(errors, "An error occurred", 1000, request.getRequestURI()); // General error
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ApiResponse<Void>> handleResourceNotFoundException(HttpServletRequest request, ResourceNotFoundException ex) {
ApiResponse<Void> response = ResponseUtil.error(ex.getMessage(), "Resource not found", 1001, request.getRequestURI()); // Resource not found error
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity<ApiResponse<Void>> handleValidationException(HttpServletRequest request, ValidationException ex) {
ApiResponse<Void> response = ResponseUtil.error(ex.getErrors(), "Validation failed", 1002, request.getRequestURI()); // Validation error
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
// Handle other specific exceptions similarly
}
現在,讓我們在示例控制器中使用標準化響應結構。
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<Product>> getProductById(@PathVariable Long id, HttpServletRequest request) {
// Fetch product by id (dummy code)
Product product = productService.findById(id);
if (product == null) {
throw new ResourceNotFoundException("Product not found with id " + id);
}
ApiResponse<Product> response = ResponseUtil.success(product, "Product fetched successfully", request.getRequestURI());
return new ResponseEntity<>(response, HttpStatus.OK);
}
@PostMapping
public ResponseEntity<ApiResponse<Product>> createProduct(@RequestBody Product product, HttpServletRequest request) {
// Create new product (dummy code)
Product createdProduct = productService.save(product);
ApiResponse<Product> response = ResponseUtil.success(createdProduct, "Product created successfully", request.getRequestURI());
return new ResponseEntity<>(response, HttpStatus.CREATED);
}
// More endpoints...
}
以下是您可能使用的常見錯誤代碼的快速參考(這些只是示例,您可以根據您的項目進行自定義):
通過標準化錯誤代碼,您可以簡化跨應用程序不同層處理錯誤的過程,從而更輕松地管理和調試問題。這些錯誤代碼可以在前端和后端維護,以確保一致的錯誤處理并向用戶提供有意義的反饋。
在Spring Boot中,實施一種清晰、一致的處理API響應的方法,不僅能使您的API更加簡潔和易于維護,而且會讓您的前端團隊(甚至未來的您)感激不盡。
原文鏈接:在 Spring Boot 中構建 API 響應的最佳方法 |作者 Rabinarayan Patra |來自 ThoughtClan 的見解 |8 月, 2024 |中等 (medium.com)