Track and monitor database errors and performance.
class ErrorTracker {
protected array $errors = [];
public function track(\Exception $e): void {
$this->errors[] = [
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
'timestamp' => time()
];
}
public function getErrors(): array {
return $this->errors;
}
}class PerformanceMonitor {
protected array $metrics = [];
public function startQuery(string $sql): void {
$this->metrics[] = [
'sql' => $sql,
'start' => microtime(true)
];
}
public function endQuery(): void {
$query = &$this->metrics[count($this->metrics) - 1];
$query['time'] = microtime(true) - $query['start'];
}
public function getSlowQueries(float $threshold = 1.0): array {
return array_filter($this->metrics, function($query) use ($threshold) {
return $query['time'] > $threshold;
});
}
}function sendAlert(string $message, array $context): void {
// Send email, SMS, or webhook
mail('admin@example.com', 'Database Error', $message);
// ...
}
try {
$users = $db->find()->from('users')->get();
} catch (DatabaseException $e) {
if ($e->getCode() >= 500) {
sendAlert('Database error', [
'error' => $e->getMessage(),
'code' => $e->getCode()
]);
}
}- Exception Hierarchy - Exception types
- Logging - Configure logging
- Retry Logic - Build retry logic