4

Everyone talks about how important exception handling is. I have never had the need to handle them until recently:

try { 
    $pdo = new PDO($dns); 
} catch (Exception $e) {
    throw new Exception($e); 
} 

Another more general example would be:

if ($something) {
    throw new Exception('Ouch! I can't do that!');
}

After a little online research, I found that many examples/solutions online simply echo them. (PDO Exception Questions - How to Catch Them) Some don't have solutions. (Catching PDOException in lower layer and re-throwing as different exception to upper layer) & (Where to catch exception in PHP MVC application?) And others, I just dont understand. (Where to catch exceptions)

Question #1: Where should I catch exceptions; in the Model or Controller of a MVCish framework?

Question #2: What should catching it do? Log it, email it, display 503?

Community
  • 1
  • 1
samland
  • 162
  • 1
  • 12
  • See also http://pbwhiteboard.blogspot.com/2010/12/on-exception-management.html (self-plug). – Paul Bilnoski Aug 05 '15 at 13:48
  • this is dealing with PDO so its database, those exceptions should be handled in the Model layer. – CodeGodie Aug 05 '15 at 13:51
  • You must catch it where you can handle it... If there is an error with the "PDO", is it something you can take care immediately (i.e. retry, or ignore it), or does it crashes the application ? (so you have to rethrow it at a higher level...) – Random Aug 05 '15 at 13:51
  • this is your MVC, you do as you wish. I would definitely log it, and display error message. – CodeGodie Aug 05 '15 at 13:55
  • @CodeGodie So if the PDO connection is lost, I should log/display a 503 in the Model? This would go against much that I have read. – samland Aug 05 '15 at 19:48

1 Answers1

1

I am a .net guy and for me best practices for catching exceptions:

  • Catch it as late as possible.
  • Write a common code to catch exception.
  • Catch it at controller level and log it somewhere with complete stack trace (ETW, Log file, DB etc.).
  • Redirect user to some good looking error page. Only controller can do this.
Deepak Bhatia
  • 1,045
  • 1
  • 8
  • 13