Jump to content

Proper Error Handling


Adamhumbug

Recommended Posts

HI All,

I am starting to write a new project and i wanted some advice on error handling in functions.

In my personal projects i have shamefully not really worried too much about error handling.

I am wanting to progress how i do things so i am looking at how best to handle errors.

I have written functions like this:

function getUserList($pdo)
{
    $sql = "SELECT fname from user";
    $data = $pdo->query($sql)->fetch();
    $out = '';
    if(!$data){
        return;
    }
    
    foreach ($data as $row) {
        $out .= $row['fname'];
    }
    return $out;
}

Basically starting the function, checking if there is data and if there is do something - i do tell the application what to display if there is no data rather than just return.

 

If there was an error here for ehatever reason there is nothing in place at all to handle this.  I have seen threads about try and catch but i have not used these before.

In modern programming with PDO what would be the best "catch all" suggestion that i could be implementing?

 

Link to comment
Share on other sites

most database errors are either due to programming mistakes or a database server that's not running. these type of errors are not recoverable by the user, and the user or hacker on a site doesn't need to know anything specific when these type of errors occur. however, you, as the programmer/developer, do want to know when these type of errors occur. therefore, when learning, developing, and debugging code/query(ies) you would like to display the raw database statement errors, so that you get immediate feedback about problems. when running your application on a live/public server, you would like to log the raw database statement errors, so that you have a record of them, and can find and fix what's causing them.

the PDO extension has always used exceptions for connection errors. you should use exceptions for all the other database statements that can fail - query, exec, prepare, and execute. in php8+, the default setting now is to use exceptions for all the database statements that can fail (for both the PDO and mysqli extensions.)

you should only catch and handle database exceptions in your code for user recoverable errors, such as when inserting/updating duplicate or out of range user submitted data. the exception catch logic would test the query error number, and setup a message for the user letting them know what was wrong with the data that they submitted, so that they can potentially correct what is wrong, and resubmit the data. for all other query error numbers,  just rethrow the exception and let php handle it. for all other types of queries, simply do nothing in your code and let php catch and handle any database exception. when php handles an exception, php will use its error related settings to control what happens with the actual error information, via an uncaught exception error (uncaught exceptions will 'automatically' get displayed/logged the same as php errors.)

Link to comment
Share on other sites

I create a simple error log for my own use and it comes in handy in debugging without the user knowing about it. I even created a simple error handler to sort the errors.

class ErrorHandler implements ErrorHandlerInterface
{
    public function handleException(Throwable $e): void
    {
        if ($e instanceof PDOException) {
            error_log('PDO Error: ' . $e->getMessage());
        } elseif ($e instanceof JsonException) {
            error_log('JSON Error: ' . $e->getMessage());
        } else {
            error_log('General Error: ' . $e->getMessage());
        }
    }
}

and in my configuration file

// Set the path for the error log file
ini_set('error_log', __DIR__ . '/error_log/error_log_file.log');

this is the most import. part errors isn't seen by the public.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.