Solution: Recover from Errors Gracefully

Let’s learn how we can recover from the missteps taken.

We'll cover the following

Anyone who enjoys dancing knows that missteps are inevitable. The secret to remaining graceful is to understand how to recover. We must give ourselves a chance to notice the cause of the mistake. Then we can react quickly and seamlessly, getting back into rhythm before anyone has seen our gaffe.

Maintain the rhythm

Checking return status and exceptions from database API calls is the best way to ensure that we haven’t missed a step. The following example shows code that checks the status after each call that could cause an error:

<?php 
try {
    $pdo = new PDO("mysql:dbname=test;host=localhost", 
       "dbuser", "dbpassword");
} catch (PDOException $e) {   //1
  report_error($e->getMessage()); 
  return; 
} 
$sql = "SELECT bug_id, summary, date_reported FROM Bugs 
   WHERE assigned_to = ? AND status = ?";
if (($stmt = $pdo->prepare($sql)) === false)  { //2
  $error = $pdo->errorInfo();
  report_error($error[2]); 
  return; 
}
if ($stmt->execute(array(1, "OPEN")) === false) { //3
  $error = $stmt->errorInfo();
  report_error($error[2]); 
  return; 
} 
if (($bug = $stmt->fetch()) === false) { //4 
  $error = $stmt->errorInfo();
  report_error($error[2]); 
  return; 
}
?>

Get hands-on with 1400+ tech skills courses.