I want to log database errors using PDO, but I do not want to have to repeatedly add logging to my catch blocks. Is there a way to force logging a PDOException?
Or would I have to create a class that extends PDO, then create a class that extends PDOExceptions and use them instead. Like the following:
try {
$dbconn = new logPDO ( ... );
//...
} catch (LogException $e ) {
//..
}
I'd like to avoid creating new classes just to work around this. It seems strange that I can't log a PDOException.
The easiest thing would be to create a function that takes PDOException
and did the logging logic.
function logPdo(PDOException $e) {
// log stuff w/ the exception instance..
}
That could be a static method on a class too. If you wanted a more OO solution though, subclassing PDO
and having it catch PDOException
then throw a subclass or custom Exception class that has a log
method or similar, that is a sound approach.
The whole setup looks unusual to me.
You don't want to add logging into your catch blocks, but want to add these blocks in numbers.
To my understanding, the general way to handle errors would be single application-wide exception handler which doing all the job - either shows the error on-screen or log it and while sending 503 to the browser. On any error, not only PDO errors. As I find every error extremely useful and deserves equal treatment.
To do so one have to set their own error handler to throw an exception and set up exception handler to log errors. And set up global try-catch block for the entire application.
While for these few non-critical parts which an application can survive without, it is possible to use a try-catch block with a logger inside, but again, I don't understand why PDO only - I'd wrap whole such block, and log every error occurred, not only PDO-risen. So, an exception of some distinct type (which triggers only logging but not halting the application on catch) can do the trick.