Обработать исключение и продолжить выполнение - PullRequest
2 голосов
/ 06 марта 2012

[РЕДАКТИРОВАТЬ - Отказ от ответственности: Это действительно плохая идея, см. Принятый ответ для реального решения.]

Я определяю свой собственный обработчик исключений, используя функцию set_exception_handler (). После выполнения обработчика мне нужен сценарий для продолжения. Есть ли способ сделать это?

Отказ от ответственности: я знаю блоки try-catch, но мне нужно динамически обрабатывать исключения. Каждый вызов Clazz :: foo () определяет свои собственные исключения, которые должны быть перехвачены моим обработчиком. Вот почему я не могу его использовать.

Пример:

class Clazz {

    private static $exceptions;

    public static function foo(array $exceptions) {
        set_exception_handler(array(__CLASS__, "exception_handler"));
        self::$exceptions = $exceptions;
        throw new RandomException;
        echo "I need this to be printed!";
    }

    public static function exception_handler($exception) {
        // process the exception in my way...
        // if $exception in self::$exceptions than 1, else 2, fi
        restore_exception_handler();
        // continue in some way, like it has never happenned
    }

}

Ответы [ 4 ]

4 голосов
/ 06 марта 2012

Просто сделайте что-то подобное в вашем файле запуска

/**
 * Set the default exception handler.
 *
 * @param Exception $exception The exception to handle
 */
$handler = function(Exception $exception)
{
    //print $exception;
};

set_exception_handler($handler);

/**
 * Register the PHP error handler. All PHP errors will fall into this
 * handler, which will convert the error into an ErrorException object
 * and pass the exception into the common exception handler.
 *
 * After all, there should never be any errors in our application. If
 * there are then we need to know about them and fix them - not ignore
 * them.
 *
 * Notice, this function will ignore the error if it is less than the
 * current error reporting level.
 */
set_error_handler(function($code, $error, $file, $line) use ($handler)
{
    if((error_reporting() & $code) === 0) return TRUE;

    $handler(new ErrorException($error, $code, 0, $file, $line));
});

/**
 * Register the PHP shutdown handler. This function will be called
 * at the end of the PHP script or on a fatal PHP error. If an error
 * has occured, we will convert it to an ErrorException and pass it
 * to the common exception handler for the framework.
 */
register_shutdown_function(function() use ($handler)
{
    if($error = error_get_last())
    {
        extract($error, EXTR_SKIP);
        $handler(new ErrorException($message, $type, 0, $file, $line));
    }
});


/**
 * Setting the PHP error reporting level to -1 essentially forces PHP to
 * report every error, and is guranteed to show every error on future
 * versions of PHP. This will insure that our handlers above are
 * notified about everything.
 */
error_reporting(-1);

/**
 * At the same time we want to disable PHP's default error display since
 * we are now using our own.
 */
ini_set('display_errors', 'Off');
2 голосов
/ 06 марта 2012

Это просто плохая идея. Я просто надеюсь, что вы не понимаете, как Исключения работают, и вы не имеете в виду вопрос.

Прежде всего, установка обработчика исключений ... Обработчик исключений вызывается, когда исключения распространяются в основной сценарий (фактически из него), и поэтому ваш сценарий завершен:

Устанавливает обработчик исключений по умолчанию, если исключение не перехвачено в блоке try / catch. Выполнение остановится после вызова обработчика исключения.

Вы должны либо использовать то, что Xeoncross предлагает , но я думаю, что у вас есть проблема с вызываемой функцией / методом, которая вызывает исключения, поэтому вы можете сделать это:

class Clazz {

    private static $exceptions;

    public static function foo(array $exceptions) {
        set_exception_handler(array(__CLASS__, "exception_handler"));
        self::$exceptions = $exceptions;
        try {
            throw new RandomException;
        } catch( Exception $e){
            self::exception_handler( $exception);
        }
        echo "I need this to be printed!";
    }

    public static function exception_handler(Exception $exception) {
    }
}
2 голосов
/ 06 марта 2012

Неа. К счастью нет способа сделать это

0 голосов
/ 18 апреля 2017

Как правило, это плохая идея, потому что код, генерирующий исключение, ожидает, что любой следующий код не будет выполнен, и я думаю, что это причина, почему он не реализован в php.

Но, возможно, это поможет вам сделать то, что вы пытаетесь сделать:

function try_throw($exception) {
    if (!Clazz::exception_handler($exception))
        throw($exception);

}

class Clazz {

    private static $exceptions;

    public static function foo(array $exceptions) {
        set_exception_handler(array(__CLASS__, "exception_handler"));
        self::$exceptions = $exceptions;
        try_throw(new RandomException);
        echo "I need this to be printed!";
    }

    public static function exception_handler($exception) {
        // process the exception in my way...
        // if $exception in self::$exceptions than 1, else 2, fi
        return true;
        // continue in some way, like it has never happenned
        // to instead throw the exception the normal way
        return false;
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...