简体   繁体   中英

Best way to handle database errors

I just wonder what is the best way to catch database errors. If error happens I would like to show some 'sorry' content to users and send an email to technical support.

I now put try-catch in connection setting file and includes this file in other functional files. It is not working properly.

Say, the database connection script called db-connect.php.

try {
  $db = new PDO('dsn', 'username', 'password');
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $ex) {
echo ('An internal error happens. The technical staff has been informed to '.
      'fix this. Sorry for any inconvenience.');
errorReport(/*title=*/"Database connection failed",
            /*code=*/$ex->getCode(), /*message=*/$ex->getMessage(),
            /*trace=*/$ex->getTraceAsString(), /*file=*/$ex->getFile(),
            /*line=*/$ex->getLine());
}

Then in another file a.php that includes db-connect:

require_once("db-connect.php");
$stmt = $db->prepare("SELECT * FROM user WHERE username=:username");
$stmt->excute(array(':username' => $uname));

Now I manually shut down database, but user would get error like

An internal error happens. The technical staff has been informed to fix this. Sorry for any inconvenience.
Notice: Undefined variable: db in a.php on line 26
Fatal error: Call to a member function prepare() on null in a.php on line 26

I do understand that variable db is not present because it is not created because of connection errors. but how could I improve this? Any help is appreciated.

The usual practice is to redirect to an error page (render redirect or url) and display some sort of helpful message to the user. You redirect so that the application no longer can process logic on potential invalid data and still render a full page.

Take a look at custom error handling functions set_error_handler and I'd advise looking into output caching to avoid potentially unwanted output as well.

This is depends upon individuals needs, how they want to show the errors. In your case I will suggest you to use error reporting settings provided by the PHP. As for development server you can use as below

error_reporting(E_ALL & E_STRICT);

And for production server you can use it as

error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING)

So your notices and warnings will not be shown on production server, but the error type of E_ERROR will be shown.

Now to handle this errors you can use try catch block as you have used already.

try {
 // Your code goes here
} catch(PDOException $ex) {
   /* Now if you have any exception in your code then you can show the 
generic message to user as 404 / not found page or woops something went wrong. Or the message you have set already as "An internal error happens. The technical staff has been informed to fix this. Sorry for any inconvenience."

With this message you can send a mail to the respective development team what exactly error comes. The email body will contain the string representation of your error message.*/
}

So in this way you can show the generic message to user and details error message via to development team via email. So whenever some critical exception or error will occur your team will get notify via email.

Hope this will help someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM