Improving error handling – Implementation

I already told that error handling needs to be improved and that I started out by printing huge amounts of PDO::errorInfos which still left me with corrupted database entries and therefor wasn’t even checked in on the repository. I left the changes dangling on the system until today when the first thing I did was a simple git checkout on the changed files.

So a fresh start…
First of I created a new file exceptions.php with just a single
class SQLException extends Exception {}
in it. Yes, this is not necessary and could’ve been done on the connection-class within the dbconnect.php file, but in favor of separation of concerns I decided to give it an own file.
Maybe the SQLException will get enhanced sometime in the future, but for now it’s ok as it is.
Another reason for exceptions.php-file is that I might add some other exceptions in the future with some fancy implementation details.

Next step was going through the methods of the connection-class and replacing the old „error handling“ (which was return false or return $errors) with throw new SQLException().
A side-effect of this was that I could get rid of all that overhead code for aggregating error-messages on loops, several returns and variables I didn’t need in the first place – so I’ll get cleaner code with this too.

Ok, now the methods of the connection class either return data, true or throw an exception, which leads me to
adding try-catch-blocks on pretty much every other file.
So going through all the create_-files I started wrapping sql-related code-blocks inside the try-part of a try-catch-block and adding a catch-block which takes care of the SQLExceptions and prints its error message.
Next I added a $connection->begin() to the beginning and an $connection->commit() to the end of the try-block and the corresponding $connection->rollback() on the catch-block of the code parts where multiple relating sql-calls occur.
As the relating connection-function calls where nested in several if-else-loops the benefit of the exceptions is that I can now eliminate most of these loops as the next sql-call will not be reached if the preceding failed.

With these changes the need for data-classes is currently not longer present, still I'm thinking about implementing these classes as that would add another layer of abstraction that might come in handy sometime.

So long

Leave a Reply