PHP Try Catch for the whole class

A simple question, but he cannot find the answer.

If I have a php class, is it possible to register an exception handler for the whole class?

The reason I want to do this is because my class uses objects that are part of my domain model. These object methods raise very explicit exceptions. I do not want these exceptions to turn into classes of a higher level, but instead they wanted to catch all these exceptions and throw them as a more general exception, for example. DomainLayerException

Therefore, I would like one area in my class to detect any number of exception lists that I define from my domain model, and throw them as a more general exception, for example.

I am currently doing this by wrapping method calls on domain objects in a catch try block. This becomes very dirty as I use more and more domain objects and their methods. It would be great to remove these catch try blocks and handle them all in one place in the ie class, if any exception is thrown in the class, it is captured by one event handler defined in the class

+7
php exception exception-handling
source share
2 answers

You can use the proxy class to make calls on your behalf and let you throw an exception:

class GenericProxy { private $obj; private $handler; public function __construct($target, callable $exceptionHandler = null) { $this->obj = $target; $this->handler = $exceptionHandler; } public function __call($method, $arguments) { try { return call_user_func_array([$this->obj, $method], $arguments); } catch (Exception $e) { // catch all if ($this->handler) { throw call_user_func($this->handler, $e); } else { throw $e; } } } } $proxy = new GenericProxy($something, function(Exception $e) { return new MyCoolException($e->getMessage(), $e->getCode(), $e); }); echo $proxy->whatever_method($foo, $bar); 

It uses the magic __call() method to intercept and forward method calls to the target.

+8
source share

EDIT: This seems like a bad idea, since "set_exception_handler is a global method. It may be in the whole world of problems if many classes set themselves up as global handlers." Thanks @Gaz_Edge for pointing this out.

Instead, you should see Jack's answer .


If I realized what you wanted, I think you can use set_exception_handler in your class.

Example:

 class myClass { public function __construct() { set_exception_handler(array('myClass','exception_handler')); } public function test(){ $mySecondClass = new mySecondClass(); } public static function exception_handler($e) { print "Exception caught in myClass: ". $e->getMessage() ."\n"; } } class mySecondClass{ public function __construct() { throw new Exception('Exception in mySecondClass'); } } $myClass = new myClass(); $myClass->test(); 

This will give: Exception caught in myClass: Exception in mySecondClass

Thus, this will lead to the conclusion of your second class exception handled by your first class handler.

Hope this helps!

0
source share

All Articles