MTVS
MTVS

Reputation: 2096

In PHP scripts, how should I deal with exceptions when connecting/sending queries to database?

Here are my possible solutions:

1) Use exit() to terminate the script. (problem: affects the loading of contents of whole page not just the data from database)

2) Embed a <div> element in the page specially for showing possible exceptions.

What's the standard approach?

Upvotes: 2

Views: 94

Answers (6)

Greeso
Greeso

Reputation: 8219

I was faced with the same problem in my project. First, I thought of a solution similar to that of david strachan, but eventualy I realized that this solution was not complete. I still need to have the debug information, but those should not be displayed to the user.

I came up with a solution that displayes to the user a message stating "System error, please try again, if the error persists, then please contact support". And also, at the same time, the error message is logged to an error-log file.

Here are the details:

function logException ($exception) {

    // Construct the error message to add to the log file
    $logDate = date("l, F j, Y  H:i:s");            
    $logMessage = "Date: " . $logDate . "\n";
    $logMessage = $logMessage . "Error Message: ". $exception->getMessage() . "\n";
    $logMessage = $logMessage . "Error Code: ". $exception->getCode() . "\n";
    $logMessage = $logMessage . "Error File: ". $exception->getFile() . "\n";
    $logMessage = $logMessage . "Error Line: ". $exception->getLine() . "\n";
    $logMessage = $logMessage . "Error Trace:\n". $exception->getTraceAsString() . "\n";
    $logMessage = $logMessage . "\n\n**************************************" . "\n\n\n";

    // Construct a log file name similar to the name of the script file that cause the error
    $info = pathinfo($exception->getFile());
    $extension = "." . $info["extension"];
    $logFile =  "../logs/" .  basename($exception->getFile(), $extension) . ".log";

    // Add the error message to the log file            
    error_log($logMessage, 3, $logFile);

    // Message to return to the user
    $errorMessage = "System error, please try again, if the error persists, then please contact support.";

    return $errorMessage;
} 


try {  
    $dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);  
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
    $stmt = $dbh->prepare("INSERT INTO table ( column ) values ( value )");  
    $stmt->execute(); 
}  

// Catching all sorts of errors, including PDO errors
catch (Exception $e) {
    $message = logException ($e);
    $data['message'] = $message;
    $data['isSuccessful'] = false;
}

Please note the following:

  1. The error message is saved to a log file
  2. The log file is saved to a logs folder. The name of the log file is derived from the name of the file that generated the error. For example, if the file that caused the error is called "script.php", then the log file will be called "script.log" and will be saved inside the logs folder.
  3. The catch statement is catching all sorts of exceptions, and is not only restricted to PDO errors.

Now, you have a problem, what if you would like to throw an exception that would like the user to see (for example, you would like to throw an exception such as "This is wrong, try agian")? Well, I did come up with a solution that is extended over this one, but it is out of your questoin. But if you still would like to know, then please let me know.

Cheers.

Upvotes: 1

david strachan
david strachan

Reputation: 7228

Option 1) is untidy as it provides a poor user experience

Option 2) is to be preferred.

Using PDO the following code will display exception and store it along with timestamp.

try {  
    $dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);  
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
    $stmt = $dbh->prepare("INSERT INTO table ( column ) values ( value )");  
    $stmt->execute(); 
    }  
catch(PDOException $e) {  
    echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing 
    file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]'). $e->getMessage()."\r\n", FILE_APPEND);  
}  

On a production site after testing the echo statement should be ammended to

echo "I'm sorry I'm afraid you can't do that.";

Upvotes: 1

Abhishek Saha
Abhishek Saha

Reputation: 2564

You should log your exceptions in a log file and use that to anaylyze what went wrong. But from user point of view, you should show them friendly statements like "Sorry your request couldnt be processed."

Upvotes: 1

Svetoslav
Svetoslav

Reputation: 4686

You have to find your own way to catch errors. I am using the

try { QUERY } catch(Exception $e) { Log and display error }

Upvotes: 0

NappingRabbit
NappingRabbit

Reputation: 1918

try - catch is the standard way I handle exceptions in php... as seen here: PHP EXCEPTIONS

try{
    some code here
}catch(Exception $e){
    failed response here
}

edit to elaborate: This is just a method of catching the exception. What to do when one is caught is a value judgement left up to the developer. if that is what the question was asking, my apologies.

Upvotes: 0

Andrew
Andrew

Reputation: 2164

There is not really a "standard" approach to how to deal with exceptions from the database. It entirely depends on the specific use case. For example, if no database connection can be established in the first case, than it is probably appropriate to redirect to an error page and send an email notification to the site administrator immediately. If, on the other hand, you cannot perform a single insert (for whatever reason), it may be more appropriate to notify the user that what they were attempting could not be accomplished and ask them to try again.

Exceptions are essentially a way of letting you, rather than the programming language or library you are using, decide how to handle what to do when things go wrong. Almost always, you will want to log the error, then it's up to you to decide the most appropriate response.

All that is to say that the appropriate way to handle exceptions is the way that makes the most sense in your application.

Upvotes: 3

Related Questions