0

I'm using PHP and PDO. Now I want to build a kind of log when things go wrong. What can go wrong with PDO?

Right now I have these tests:

Connection test

try {
    $this->pdo = new PDO($dsn, $credentials['user'], $credentials['pass'], $options);
} catch(Exception $e) {
    $this->file->put( date('Y-m-d') . '.txt', 'log', 'Database error');
}

Execute test

try {
    $stmt->execute();
} catch(Exception $e) {
    $this->error->log('SQL', 'query error');
}

Any more tests that are good?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • 1
    Why don't you use the message of the exception? That would be far more detailed about what happened. – halloei Feb 02 '16 at 14:26
  • @halloei Good point! I probably will. – Jens Törnell Feb 02 '16 at 14:27
  • Why are you `catch`ing in the first place? The error will get logged automatically in all its glory if you don't catch. It also has the benefit of keeping your program sane; because what are you going to do if you can't create a database connection or execute a query? Realistically: probably nothing. Dying is the only real option, and an uncaught exception does that nicely. – deceze Feb 02 '16 at 14:29
  • @deceze I have a really simple admin tool to show my errors. If an error accur like 10 times in a row I will mail myself about it so I can fix the problem. – Jens Törnell Feb 02 '16 at 14:33
  • Monitor your PHP log and do the same thing...!? – deceze Feb 02 '16 at 14:34
  • @deceze So what you say is that I should completly skip all try catch everywhere in my code, activate error reporting to PHP log file and parse that file in my tool instead? – Jens Törnell Feb 02 '16 at 14:41
  • Exactly. Whether or not to `catch` an exception is a decision informed by your application design. You only `catch` an exception if you know what to do with it. You don't catch it just to log it and then continue with the rest of your app as if nothing happened. There are plenty of tools out there for exactly the kind of error monitoring you're trying to do, and you should not, nay, must not rewrite your entire application for that. Look at great services like New Relic for instance. – deceze Feb 02 '16 at 14:45
  • @deceze Ok then. It will probably save me much time. New Relic seemed far too advanced for my taste. I will try http://pimpmylog.com/ instead, which looks more like the tool I was going to create. Thanks! – Jens Törnell Feb 02 '16 at 15:18

1 Answers1

2

You do not log your exception message in your logs. I suggest you to do something like this into your catch :

$this->error->log('SQL', $e . PHP_EOL);

This will give you more understandable and readable logs.

Regarding the exceptions to catch with PDO, you may read that post : How to handle PDO exceptions

Community
  • 1
  • 1
Okipa
  • 551
  • 4
  • 18