Exceptional Exceptions: Cleverly throwing Exceptions in PHP

TIL, from the Engagor Clarabridge Development Blog: When creating an \Exception in PHP (including your own extended classes), you can pass in a third argument named $previous. It defines the previous \Exception used for exception chaining, leaving you with better errors for debugging:

try {
    $this->doSomeImportantStuffWith($foo);
} catch (VeryDescriptiveException $e) {
    // do some stuff here
    throw new SomethingWentWrongException('oh no!', 0, $e);
}
Fatal error: Uncaught VeryDescriptiveException: hello there! in test.php:15
Stack trace:
#0 /Users/toon/Projects/devblog/test.php(23): Test->doSomeImportantStuffWith('test')
#1 /Users/toon/Projects/devblog/test.php(34): Test->withPrevious()
#2 {main}

Next SomethingWentWrongException: oh no! in test.php:6
Stack trace:
#0 /Users/toon/Projects/devblog/test.php(34): Test->withPrevious()
#1 {main}
  thrown in /Users/toon/Projects/devblog/test.php on line 6

The tip to use named constructors for Exceptions also is something I’ll be using from now on 🙂

Clarabridge Development Blog: Exceptional Exceptions →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.