Treat error when connecting to Mysql with PDO

Asked

Viewed 626 times

-1

People would like to treat 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();
  }

}

But the custom message is not showing, only the Fatal Error: < path of the.php file > on line 11 And I don’t want the file name and the error line to appear, only the message.

  • What is the complete error message? A Fatal Error is not an exception.

  • Has a native function of PHP that can meet your need simply, she calls PDO::errorInfo which has a function similar to mysqli_error. Link:http://php.net/manual/en/pdo.errorinfo.php

  • Yes, Fatal Error is not caught by catch because it is not an exception. I will test with PDO::errorInfo, thanks for the tip.

1 answer

0

I found that it is not possible to catch Fatal Errors because this kind of error makes the program stop.

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

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 believe this is the best way to show only the personalized message.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.