Handling error connecting to MySQL with PDO

-1

I would like to handle the error that occurs if the MySQL server is not running, I want only one message to appear so I made the following code:

function mensagemErro () {
  throw new \Exception("Error connecting to database");
}

function connect() {
  try {
    $pdo = new \PDO("mysql:host=localhost;dbname=DB;charset=utf8", 'root', 'root');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

    return $pdo;
  } catch (Exception $e) {
      mensagemErro();
      echo $e->getMessage();
  }

}

However, the custom message is not appearing, only the Fatal Error: < path of the .php file > online 11 And I do not want the file name and error line to appear, just the message.

    
asked by anonymous 03.01.2019 / 16:10

1 answer

0

I discovered that it is not possible to catch Fatal Errors with catch because this type of error causes the program to stop.

Then I reformulated the function that connects to MySQL starting by disabling this type of error with ini_set ('display_errors', 0); and using PDOException PDO error handling:

function connect() {
  try {
    ini_set('display_errors', 0);
    $pdo = new \PDO("mysql:host=localhost;dbname=BassamBrasil;charset=utf8", 'root', 'root');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

    return $pdo;
  } catch(PDOException $e) {
    //cho 'ERROR: ' . $e->getMessage();
    echo 'ERROR: Error connecting to database';
  }

}

Well, I think this is the best way to show only the custom message.

    
03.01.2019 / 16:35