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 🙂