-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProgram.cs
More file actions
78 lines (72 loc) · 1.99 KB
/
Copy pathProgram.cs
File metadata and controls
78 lines (72 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using SerpApi;
// Demonstrate all exception types
// 1. Missing API key
Console.WriteLine("=== SerpApiKeyException (empty key) ===");
try
{
var bad = new SerpApiClient("");
}
catch (SerpApiKeyException ex)
{
Console.WriteLine($" Caught: {ex.Message}");
}
// 2. Invalid API key (requires network)
var apiKey = args.Length > 0 ? args[0] : Environment.GetEnvironmentVariable("SERPAPI_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("\nSkipping network tests (no API key).");
Console.WriteLine("Usage: dotnet run -- <API_KEY>");
return;
}
Console.WriteLine("\n=== SerpApiKeyException (invalid key) ===");
using (var client = new SerpApiClient("invalid_key_12345"))
{
try
{
using var results = await client.SearchAsync(new Dictionary<string, string>
{
["engine"] = "google",
["q"] = "test"
});
}
catch (SerpApiKeyException ex)
{
Console.WriteLine($" Caught: {ex.Message}");
}
}
// 3. Timeout
Console.WriteLine("\n=== SerpApiTimeoutException ===");
using (var client = new SerpApiClient(apiKey, new SerpApiClientOptions
{
Timeout = TimeSpan.FromMilliseconds(1) // impossibly short
}))
{
try
{
using var results = await client.SearchAsync(new Dictionary<string, string>
{
["engine"] = "google",
["q"] = "timeout test"
});
}
catch (SerpApiTimeoutException ex)
{
Console.WriteLine($" Caught: {ex.Message}");
}
}
// 4. Successful request with error handling
Console.WriteLine("\n=== Successful search with error handling ===");
using var safeClient = new SerpApiClient(apiKey);
try
{
using var results = await safeClient.SearchAsync(new Dictionary<string, string>
{
["engine"] = "google",
["q"] = "error handling best practices"
});
Console.WriteLine($" Success! Got {results.OrganicResults?.GetArrayLength()} results");
}
catch (SerpApiException ex)
{
Console.WriteLine($" Error: {ex.Message}");
}