Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you handle database connection errors gracefully? Database connection errors को gracefully कैसे handle करें?

Answer

Set PDO to throw exceptions, catch them, log details for debugging, and show a generic message to users without exposing sensitive info.

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
} catch (PDOException $e) {
    error_log('DB connection failed: ' . $e->getMessage());
    http_response_code(500);
    die('A database error occurred. Please try again later.');
}

Never echo raw exception messages to end users in production - they can reveal database structure, credentials, or file paths to attackers.

PDO को exceptions throw करने के लिए set करें, catch करें, debugging के लिए log करें, और users को generic message दिखाएं।

try {
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
} catch (PDOException $e) {
    error_log('DB connection failed: ' . $e->getMessage());
    http_response_code(500);
    die('A database error occurred. Please try again later.');
}

Production में users को raw exception message कभी न दिखाएं - इससे database structure लीक हो सकता है।

Was this answer clear?