Kuldeep Thakur
Kuldeep Thakur

Reputation: 215

try catch in php pdo, doing it right way

I am using php pdo with postgres. I am using core php, no mvc, no classes and objects. I have some doubts in my mind since i am new to development, :-

please some one clear my doubts about this.

Upvotes: 2

Views: 334

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 158007

  1. Only if you have a certain scenario to handle a particular error. For example, a duplicated unique key, for which you have a fall-back scenario. (note that you should always check for this particular error, and re-throw the exception otherwise).
    But for a regular query, only to handle an arbitrary error - just like @skyboyer said - no way. The exception should bubble up to a site-wide handler.
  2. Again, it depends. If is a special handling scenario, do whatever you have in mind for the scenario. But for the arbitrary error, it is agreed upon to halt the code execution, as your code could yield unpredictable results.
  3. That's two questions in one.
    • it's perfectly OK to have a global try catch which will act as a site-wide exception handler, wrapping the whole code.
    • as of the function to run all your queries - it's a brilliant idea by itself, but it has nothing to do with error handling. Simply because database errors are no different from any other error on your site and thus should be treated exactly the same way. Therefore it makes no sense to write a dedicated try-catch for the query function. Just let it throw an Exception and then handle that exception as any other error on your site.
  4. Pretty much the same way as non-AJAX errors. Again - just like @skyboyer said - make your handler to return 500 HTTP status and then your AJAX calling code will know there was an error. That's enough

I wrote an article where tried to explain all there matters, PHP Error reporting which you may find interesting.

Upvotes: 4

skyboyer
skyboyer

Reputation: 23763

There are too many questions and they are too generic. But in most cases:

  1. No way
  2. it's up to you, your app's logic and particular case. Say if there is water leak somewhere in the city is it expected to stop water supply system completely? Typically there is concrete module/part that does not make sense to process further once DB query fails. And only that module/part should exit/stop.
  3. it's better not doing your own wrapping around PDO. in most cases you will just make code harder to maintain without any real benefit.
  4. typically the best solution is to return some HTTP error(404 Not Found or 500 Internal Server Error) letting client code to know "sorry, you cannot get this information yet"; how client code will handle such an error - it depends on your client code's logic/flow

Upvotes: 3

Related Questions