سؤال

try {
    self::$dbinstance = new PDO(
        "mysql:host=$c[host];dbname=$c[dbname]", $c['user'], $c['password']
    );

    self::$dbinstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} 
catch(PDOException $e) {
    echo "Errors" . $e->getMessage();
}

In the above code, if PDO fails to connect to the host, a fatal error reveals the username and password.

Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2003]
Can't connect to MySQL server on '172.25.102.65' (10060)' in
D:\xampp\htdocs\mytest\wh_client_2.1\classes\importmodule-class.php:33 Stack trace: #0
D:\xampp\htdocs\mytest\wh_client_2.1\classes\importmodule-class.php(33): PDO-
>__construct('mysql:host=172....', 'host', 'password') #1

One possible way is to turn the display_error=0 off in php.ini, but this way I won't able to know that when my host is not responding.

Is there a way I can modify the error message?

هل كانت مفيدة؟

المحلول

There is a difference between error handling and error reporting.

  • Error handling is the process of preventing your end users to see any stack trace, vital information or automatically generated error messages. It can also modify the way your script runs by using a try catch block.
  • Error reporting defines which information will be reported by a given script.

To handle errors properly, I think that ini_set('display_errors',0); is the better approach. You do not want any error message displaying on the screen.

However, I want to have all possible information on errors, so I use error_reporting(E_ALL);.

Errors are written in a file, error_log, which usually resides at the same level as your index.php (or any PHP file called directly). You can also access it from your cPanel.


Your error is probably uncaught because your code is in a namespace, whereas you want to catch the global namespace PDOException. Use a \ to indicate your script you're looking for the global PDOException. Once you catch your error, you can echo the content you want, using the normal methods of the PDOException class.

try {
    $db = new PDO (/*connection infos*/);
}
catch (\PDOException $e) {
    switch ($e->errorCode()) {
        case 'HY000':
        // Or whatever error you are looking for
        // here it's the general error code
            mail('your@email.com','connection problem',$e->getTraceAsString());
            $db = new PDO (/*rollback connection infos of a local database*/);
            break;
    }
}

That would send you a mail, containing the trace of the error, preventing your user from seeing it while telling you something is wrong.

Here is the reference for the error codes returned by PDO statements.

نصائح أخرى

When your host is not responding you will know all right - your host will stop responding. Then you have to peek into the error log and find the error message with the particular error.

So, just keep with display_errors=0 as it's a must-have in a production environment anyway.

No, don't try to throw the exception as it will spit out such critical information... Handle them with some appropriate custom error messages and handle those exceptions inside your custom logging functions...

You must be doing something similar to this...

<?php

try {    
    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'uname', 'pass');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->query('bla bla bla bla'); //<---- This will definitely fail!!!!
} catch(PDOException $ex) {
    echo "An error occurred!";
    file_put_contents('somefile.txt', $ex->getMessage(), FILE_APPEND);
}

As you can see, the above query is indeed going to fail. So the end user will be seeing just An error occurred! message, but the error will be logged to your somefile.txt file.

You can do something like this:

<?php
// connect
try
{
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
}
catch (PDOException $e)
{
    $dbh = NULL;
}

// check if connected
if($dbh)
{
    // run queries
}
else
{
    die('Oops! Our server has encountered an error, please try again later');
}
?>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top