1 year ago

#381460

test-img

theking2

How to catch PDO connection exception

I have this code:

        $db_options = 
            [ \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
            , \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_BOUND
            , \PDO::ATTR_ERRMODE => \PDO::ERRMODE_SILENT
            , \PDO::ATTR_PERSISTENT => true
            , \PDO::ATTR_EMULATE_PREPARES => false
            ];

        try {
            $this-> connection =  new \PDO( $dsn, $db_user, $db_pass, $db_options );
        } catch( \PDOException $e ) {
            throw new DatabaseException( DatabaseException::ERR_CONNECTION, $e );
        }

But a PDOException is thown at the new \PDO line: Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it..

What would be the proper way to catch these PDO errors?

(Btw. before you answer: yes, the database wasn't running on that machine, I know)

[EDIT] For completeness the DatabaseException:

class DatabaseException extends \Exception {
    const ERROR_START = 0x2000; // Vieww errors start here
    const ERR_CONNECTION = DatabaseException::ERROR_START+0;
    const ERR_STATEMENT = DatabaseException::ERROR_START+1;
    const ERR_EXCECUTE = DatabaseException::ERROR_START+2;
    private static $messageEN = array(
        DatabaseException::ERR_CONNECTION => "Could not connect to database",
        DatabaseException::ERR_STATEMENT => 'Statement error: %s',
        DatabaseException::ERR_EXCECUTE => 'Statement execute error: %s'
    );
            
    /**
     * __construct
     *
     * @param  int $code
     * @param  \Exception $previous
     * @param  string $message
     * @return \db\DatabaseException
     */
    public function __construct (int $code, ?\Exception $previous = NULL, ?string $message = NULL )
    {
        if( $message ){
            parent::__construct( sprintf(self::$messageEN[$code], $message), $code, $previous );
         } else {
            parent::__construct( self::$messageEN[$code], $code, $previous );
        }
    }
}

php

exception

pdo

0 Answers

Your Answer

Accepted video resources