Get exception context in PHP

If you use a custom error handler in PHP, you can see the error context (the value of all variables in the place where this happened). Is there a way to do this for exceptions? I mean getting the context, not setting up the exception handler.

+5
source share
4 answers

You can attach the context to your exception manually. I have never tried, but it would be interesting to create a custom exception that in the constructor raises and saves get_defined_vars()for later retrieval.
This will be a tough exception :-)

proof of concept:

class MyException extends Exception()  {
    protected $throwState;

    function __construct()   {
        $this->throwState = get_defined_vars();
        parent::__construct();
    }

    function getState()   {
        return $this->throwState;
    }
}

better:

class MyException extends Exception implements IStatefullException()  {
    protected $throwState;

    function __construct()   {
        $this->throwState = get_defined_vars();
        parent::__construct();
    }

    function getState()   {
        return $this->throwState;
    }

    function setState($state)   {
        $this->throwState = $state;
        return $this;
    }
}

interface  IStatefullException { function getState(); 
      function setState(array $state); }


$exception = new MyException();
throw $exception->setState(get_defined_vars());
+8

:

class ContextException extends Exception {

    public $context;

    public function __construct($message = null, $code = 0, Exception $previous = null, $context=null) {
        parent::__construct($message, $code, $previous);
        $this->context = $context;
    }

    public function getContext() {
        return $this->context;
    }
}

.

+2

PHP:

http://www.php.net/manual/en/language.exceptions.extending.php

Exception:

final public  function getMessage();        // message of exception
final public  function getCode();           // code of exception
final public  function getFile();           // source filename
final public  function getLine();           // source line
final public  function getTrace();          // an array of the backtrace()
final public  function getPrevious();       // previous exception
final public  function getTraceAsString();  // formatted string of trace

, , . , , , , , , , . , , .

+1

All Articles