import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
public class ApiGuard {
private final Map<String, Object> apiHandlers;
public ApiGuard() {
this.apiHandlers = new HashMap<>();
}
public void registerHandler(String endpoint, Supplier<Object> handler) {
apiHandlers.put(endpoint, handler);
}
public Object execute(String endpoint) {
// Check if the endpoint has a registered handler
if (apiHandlers.containsKey(endpoint)) {
try {
// Execute the handler
return apiHandlers.get(endpoint).get();
} catch (Exception e) {
// Fallback logic in case of handler execution failure
System.err.println("Error executing endpoint " + endpoint + ": " + e.getMessage());
return fallback(); // Return a default value or handle the error
}
} else {
// Endpoint not found, return a default value or handle the error
System.err.println("Endpoint " + endpoint + " not found.");
return fallback();
}
}
// Define the fallback logic
private Object fallback() {
// Replace with your desired fallback behavior
System.out.println("Using fallback logic.");
return "Fallback Value";
}
public static void main(String[] args) {
ApiGuard guard = new ApiGuard();
// Register API handlers
guard.registerHandler("/users", () -> "User data");
guard.registerHandler("/products", () -> "Product catalog");
// Execute API endpoints
System.out.println(guard.execute("/users")); // Output: User data
System.out.println(guard.execute("/products")); // Output: Product catalog
System.out.println(guard.execute("/nonexistent")); // Output: Endpoint not found, then Fallback Value
}
}
Add your comment