-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy path01-exception-handling.php
More file actions
384 lines (312 loc) · 12.3 KB
/
Copy path01-exception-handling.php
File metadata and controls
384 lines (312 loc) · 12.3 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
<?php
declare(strict_types=1);
/**
* Exception Handling Examples
*
* This example demonstrates how to use the new exception hierarchy
* for better error handling in your applications.
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\PdoDb;
use tommyknocker\pdodb\exceptions\AuthenticationException;
use tommyknocker\pdodb\exceptions\ConnectionException;
use tommyknocker\pdodb\exceptions\ConstraintViolationException;
use tommyknocker\pdodb\exceptions\DatabaseException;
use tommyknocker\pdodb\exceptions\QueryException;
use tommyknocker\pdodb\exceptions\ResourceException;
use tommyknocker\pdodb\exceptions\TimeoutException;
use tommyknocker\pdodb\exceptions\TransactionException;
$db = createExampleDb();
$driver = getCurrentDriver($db);
echo "=== Exception Handling Examples (on {$driver}) ===\n\n";
// Example 1: Basic exception handling with specific types
echo "1. Basic Exception Handling\n";
echo "----------------------------\n";
try {
// Use Schema Builder to drop and create table (demonstrates proper library usage)
$schema = $db->schema();
$schema->dropTableIfExists('users');
// Create table using Schema Builder - demonstrates proper usage of library API
$schema->createTable('users', [
'id' => $schema->primaryKey(),
'email' => $schema->string(255)->unique(),
'name' => $schema->string(255)
]);
// Insert first user
$db->find()->from('users')->insert(['email' => 'test@example.com', 'name' => 'Test User']);
// Try to insert duplicate email - this will cause constraint violation
$db->find()->from('users')->insert(['email' => 'test@example.com', 'name' => 'Another User']);
} catch (ConstraintViolationException $e) {
echo "Constraint Violation: {$e->getMessage()}\n";
echo "Driver: {$e->getDriver()}\n";
echo "Retryable: " . ($e->isRetryable() ? 'Yes' : 'No') . "\n";
echo "Category: {$e->getCategory()}\n";
echo "Constraint: " . ($e->getConstraintName() ?? 'Unknown') . "\n";
echo "Table: " . ($e->getTableName() ?? 'Unknown') . "\n";
echo "Column: " . ($e->getColumnName() ?? 'Unknown') . "\n";
echo "Context: " . json_encode($e->getContext()) . "\n";
} catch (AuthenticationException $e) {
echo "Authentication Error: {$e->getMessage()}\n";
echo "Driver: {$e->getDriver()}\n";
echo "Retryable: " . ($e->isRetryable() ? 'Yes' : 'No') . "\n";
} catch (DatabaseException $e) {
echo "Database Error: {$e->getMessage()}\n";
echo "Driver: {$e->getDriver()}\n";
echo "Category: {$e->getCategory()}\n";
echo "Retryable: " . ($e->isRetryable() ? 'Yes' : 'No') . "\n";
}
echo "\n";
// Example 2: Constraint violation handling
echo "2. Constraint Violation Handling\n";
echo "--------------------------------\n";
try {
// Use Schema Builder to drop and create table (demonstrates proper library usage)
$schema = $db->schema();
$schema->dropTableIfExists('users');
// Create table using Schema Builder - demonstrates proper usage of library API
$schema->createTable('users', [
'id' => $schema->primaryKey(),
'email' => $schema->string(255)->unique()->notNull(),
'name' => $schema->string(255)->notNull()
]);
// Insert first user
$db->find()->table('users')->insert([
'email' => 'test@example.com',
'name' => 'Test User'
]);
// Try to insert duplicate email (this will fail)
$db->find()->table('users')->insert([
'email' => 'test@example.com', // Duplicate!
'name' => 'Another User'
]);
} catch (ConstraintViolationException $e) {
echo "Constraint Violation: {$e->getMessage()}\n";
echo "Constraint: {$e->getConstraintName()}\n";
echo "Table: {$e->getTableName()}\n";
echo "Column: {$e->getColumnName()}\n";
echo "Query: {$e->getQuery()}\n";
echo "Retryable: " . ($e->isRetryable() ? 'Yes' : 'No') . "\n";
// Handle the constraint violation appropriately
echo "Handling: Updating existing user instead of inserting\n";
// Update existing user
$affected = $db->find()
->table('users')
->where('email', 'test@example.com')
->update(['name' => 'Updated User']);
echo "Updated {$affected} user(s)\n";
}
echo "\n";
// Example 3: Transaction error handling
echo "3. Transaction Error Handling\n";
echo "-----------------------------\n";
try {
// Use Schema Builder to drop and create table (demonstrates proper library usage)
$schema = $db->schema();
$schema->dropTableIfExists('accounts');
// Create table using Schema Builder - demonstrates proper usage of library API
$schema->createTable('accounts', [
'id' => $schema->primaryKey(),
'balance' => $schema->decimal(10, 2)->notNull()->defaultValue(0)
]);
// Insert test account
$db->find()->table('accounts')->insert(['balance' => 1000]);
// Start transaction
$db->startTransaction();
try {
// Simulate concurrent update (this would cause issues in real scenario)
$db->find()
->table('accounts')
->where('id', 1)
->update(['balance' => 500]);
// Commit transaction
$db->commit();
echo "Transaction completed successfully\n";
} catch (TransactionException $e) {
echo "Transaction Error: {$e->getMessage()}\n";
echo "Retryable: " . ($e->isRetryable() ? 'Yes' : 'No') . "\n";
// Rollback and potentially retry
$db->rollBack();
echo "Transaction rolled back\n";
if ($e->isRetryable()) {
echo "Retrying transaction...\n";
// In real application, implement retry logic here
}
}
} catch (DatabaseException $e) {
echo "Database Error: {$e->getMessage()}\n";
}
echo "\n";
// Example 4: Comprehensive error handling with logging
echo "4. Comprehensive Error Handling with Logging\n";
echo "-------------------------------------------\n";
function handleDatabaseError(DatabaseException $e): void
{
$errorData = $e->toArray();
echo "=== Error Details ===\n";
echo "Type: {$errorData['exception']}\n";
echo "Message: {$errorData['message']}\n";
echo "Code: {$errorData['code']}\n";
echo "Driver: {$errorData['driver']}\n";
echo "Category: {$errorData['category']}\n";
echo "Retryable: " . ($errorData['retryable'] ? 'Yes' : 'No') . "\n";
if ($errorData['query']) {
echo "Query: {$errorData['query']}\n";
}
if (!empty($errorData['context'])) {
echo "Context: " . json_encode($errorData['context']) . "\n";
}
// Additional details for specific exception types
if ($e instanceof ConstraintViolationException) {
echo "Constraint: {$e->getConstraintName()}\n";
echo "Table: {$e->getTableName()}\n";
echo "Column: {$e->getColumnName()}\n";
}
if ($e instanceof TimeoutException) {
echo "Timeout: {$e->getTimeoutSeconds()}s\n";
}
if ($e instanceof ResourceException) {
echo "Resource Type: {$e->getResourceType()}\n";
}
echo "===================\n";
}
try {
$db = createExampleDb();
// This will fail with a query error
$db->rawQuery('SELECT * FROM nonexistent_table');
} catch (QueryException $e) {
echo "Query Error occurred:\n";
handleDatabaseError($e);
} catch (DatabaseException $e) {
echo "Database Error occurred:\n";
handleDatabaseError($e);
}
echo "\n";
// Example 5: Retry logic with exception types
echo "5. Retry Logic with Exception Types\n";
echo "-----------------------------------\n";
function executeWithRetry(callable $operation, int $maxRetries = 3): mixed
{
$attempt = 0;
$lastException = null;
while ($attempt < $maxRetries) {
try {
return $operation();
} catch (ConnectionException $e) {
$lastException = $e;
$attempt++;
if ($attempt < $maxRetries) {
echo "Connection error (attempt {$attempt}/{$maxRetries}): {$e->getMessage()}\n";
echo "Retrying in " . (2 ** $attempt) . " seconds...\n";
sleep(2 ** $attempt);
}
} catch (TimeoutException $e) {
$lastException = $e;
$attempt++;
if ($attempt < $maxRetries) {
echo "Timeout error (attempt {$attempt}/{$maxRetries}): {$e->getMessage()}\n";
echo "Retrying in " . (2 ** $attempt) . " seconds...\n";
sleep(2 ** $attempt);
}
} catch (ResourceException $e) {
$lastException = $e;
$attempt++;
if ($attempt < $maxRetries) {
echo "Resource error (attempt {$attempt}/{$maxRetries}): {$e->getMessage()}\n";
echo "Retrying in " . (2 ** $attempt) . " seconds...\n";
sleep(2 ** $attempt);
}
} catch (TransactionException $e) {
$lastException = $e;
$attempt++;
if ($attempt < $maxRetries) {
echo "Transaction error (attempt {$attempt}/{$maxRetries}): {$e->getMessage()}\n";
echo "Retrying in " . (2 ** $attempt) . " seconds...\n";
sleep(2 ** $attempt);
}
} catch (DatabaseException $e) {
// Non-retryable errors
throw $e;
}
}
throw $lastException;
}
try {
$result = executeWithRetry(function() {
$db = createExampleDb();
return $db->rawQuery('SELECT 1 as test');
});
echo "Operation succeeded: " . json_encode($result[0]) . "\n";
} catch (DatabaseException $e) {
echo "Operation failed after retries: {$e->getMessage()}\n";
}
echo "\n";
// Example 6: Error monitoring and alerting
echo "6. Error Monitoring and Alerting\n";
echo "-------------------------------\n";
class DatabaseErrorMonitor
{
private array $errorCounts = [];
private array $criticalErrors = [];
public function handleError(DatabaseException $e): void
{
$category = $e->getCategory();
$this->errorCounts[$category] = ($this->errorCounts[$category] ?? 0) + 1;
// Log critical errors
if ($this->isCriticalError($e)) {
$this->criticalErrors[] = [
'timestamp' => date('Y-m-d H:i:s'),
'exception' => $e::class,
'message' => $e->getMessage(),
'category' => $category,
'driver' => $e->getDriver(),
'query' => $e->getQuery(),
'context' => $e->getContext()
];
$this->sendAlert($e);
}
// Log error for monitoring
$this->logError($e);
}
private function isCriticalError(DatabaseException $e): bool
{
return $e instanceof AuthenticationException ||
$e instanceof ResourceException ||
($e instanceof ConnectionException && !$e->isRetryable());
}
private function sendAlert(DatabaseException $e): void
{
echo "🚨 CRITICAL ALERT: " . $e::class . "\n";
echo " Message: {$e->getMessage()}\n";
echo " Driver: {$e->getDriver()}\n";
echo " Category: {$e->getCategory()}\n";
echo " Time: " . date('Y-m-d H:i:s') . "\n";
echo " Action Required: Immediate investigation needed\n\n";
}
private function logError(DatabaseException $e): void
{
echo "📝 Error logged: " . $e::class . " - {$e->getMessage()}\n";
}
public function getErrorStats(): array
{
return [
'counts' => $this->errorCounts,
'critical_count' => count($this->criticalErrors),
'critical_errors' => $this->criticalErrors
];
}
}
$monitor = new DatabaseErrorMonitor();
// Simulate various errors
try {
$db = createExampleDb();
$db->rawQuery('SELECT * FROM nonexistent_table');
} catch (QueryException $e) {
$monitor->handleError($e);
}
// Display error statistics
$stats = $monitor->getErrorStats();
echo "\nError Statistics:\n";
echo "Total errors by category: " . json_encode($stats['counts']) . "\n";
echo "Critical errors: {$stats['critical_count']}\n";
echo "\n=== Exception Handling Examples Complete ===\n";