开发者

Send uncaught exceptions to a particular method

开发者 https://www.devze.com 2023-02-10 08:47 出处:网络
I have a custom exception class with a show() method that shows exceptions in a pretty way. In some fatal errors I left the exceptions uncaught so the programs exists intermediately, but I would like

I have a custom exception class with a show() method that shows exceptions in a pretty way.

In some fatal errors I left the exceptions uncaught so the programs exists intermediately, but I would like those exceptions to be shown with the show method.

Can this be done?

class MyException extends Exception
{
    public $e;
    public function _contruct($message, $code = 0)
    {
        parent::_construct($message, $code);
    }

    public function show()
    {
        if(!defined('DEBUG')) define('DEBUG', FALSE);
        p("Error: " . $this->getMessage());
        if(DEBUG)
        {
            p('Stack trace');
            p($this->getFile() . ' (' . $this->getLine() . ')');
            pre(get_dump($this->getTraceAsString()));
        }
    }
}

Solution

class MyException extends Exception
{
    public $e;
    public function _contruct($message, $code = 0)
    {
        parent::_construct($message, $code);
    }

    public function show()
    {
        MyException::realShow($this);
    }

    static function realShow($e)
    {
        if(!defined('DEBUG')) define('DEBUG', FALSE);
        p("Error: " . $e->getMessage());
        if(DEBUG)
        {
            p('Stack trace');
            p($e->getFile() . ' (' . $e->getLine() . ')');
            pre(get_dump($e->getTraceAsString()));
        }
    }
}

If somebody has a better way, I'开发者_StackOverflowm are all eyes.


Sure, you can set an uncaught exception handler function using the set_exception_handler function:

function exception_handler($ex) {
   //$ex will be the thrown Exception object
}

set_exception_handler('exception_handler');

From the docs:

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called

Also, you don't need to override the constructor, the parent class' constructor will be invoked automatically if it is not overridden.


You should not use the exception system in PHP.

As stated in the documentation:

The PHP exception system causes certain overheads per object even before they are thrown. This requires meticulous memory handling and is only recommended for system critical exceptions (uncontrollable either by you, or the user). For more common things it is better to utilise trigger_error on custom non-Exception objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号