1

I'm writing a singleton wrapper for database calls in my site.

When catching exceptions from PDO, should I terminate the script or treat them as warnings?

Is there a way to determine the severity of an exception thrown by PDO? For example, is there an equivalent of PHP's notices?

  • @PeeHaa How does throwing notices instead of error help? Also why do you consider singleton an anti-pattern? I don't see how it is similar to `global`s. –  Dec 09 '12 at 23:16
  • Sorry. [I meant exceptions](http://php.net/manual/en/class.pdoexception.php). – PeeHaa Dec 09 '12 at 23:20
  • @cainmi: I'd recommend you watch this Google tech talk (http://www.youtube.com/watch?v=-FRm3VPhseI). It really explains the inherent faults with singletons. It's a little long, but it's worth every minute of your time. – Ayush Dec 09 '12 at 23:20
  • 1
    Because when using a singleton you are amongst others tightly coupling code, hiding dependencies etc. You could check out an answer I wrote some time ago about using `global` and you will see that a singleton has the exact same problems (http://stackoverflow.com/questions/11923272/use-global-variables-in-a-class/11923384). – PeeHaa Dec 09 '12 at 23:22
  • Thanks, I'll check it out, and look and getting rid of the singleton. I originally made a mistake in my question, I'm actually catching PDO exceptions. My question still stands though, should I terminate the script? –  Dec 09 '12 at 23:49

1 Answers1

1

No, database errors should not be fatal and end your execution - if not your specification tells you otherwise.

As @PeeHaa say, errors should throw an exception instead of killing the script. Certain drivers might have this option as per default, but usually with the MySQL driver you'll need to set the error mode when connecting.

It is probably recommended that you allow for Exceptions to be thrown, so that you can catch the errors and perform alternative measures if the main procedure fails.

try {
    $sthmt->execute();
}
catch (Exception $error) {
    // Opps, the statement failed, revert or initiate error procedure
}
Daniel
  • 3,726
  • 4
  • 26
  • 49
  • Sorry, I wrote errors, but meant exceptions - I am catching exceptions and logging them. –  Dec 09 '12 at 23:52