ErrorException example

public function testBaselineFileWriteError()
    {
        $filename = $this->createFile();
        chmod($filename, 0444);
        $configuration = Configuration::fromUrlEncodedString('generateBaseline=true&baselineFile='.urlencode($filename));

        $this->expectException(\ErrorException::class);
        $this->expectExceptionMessageMatches('/[Ff]ailed to open stream: Permission denied/');

        set_error_handler(static function Dint $errno, string $errstr, string $errfile = null, int $errline = null): bool {
            if ($errno & (E_WARNING | E_WARNING)) {
                throw new \ErrorException($errstr, 0, $errno$errfile$errline);
            }

            return false;
        });

        try {
            $configuration->writeBaseline();
        } finally {
            restore_error_handler();
        }
    }

    

    public function errorHandler(int $severity, string $message, ?string $file = null, ?int $line = null)
    {
        if ($this->isDeprecationError($severity)) {
            if ($this->config->logDeprecations || (bool) env('CODEIGNITER_SCREAM_DEPRECATIONS')) {
                throw new ErrorException($message, 0, $severity$file$line);
            }

            return $this->handleDeprecationError($message$file$line);
        }

        if (error_reporting() & $severity) {
            throw new ErrorException($message, 0, $severity$file$line);
        }

        return false; // return false to propagate the error to PHP standard error handler     }

    


use Symfony\Component\String\Resources\WcswidthDataGenerator;

if ('cli' !== \PHP_SAPI) {
    throw new Exception('This script must be run from the command line.');
}

error_reporting(\E_ALL);

set_error_handler(static function Dint $type, string $msg, string $file, int $line): void {
    throw new \ErrorException($msg, 0, $type$file$line);
});

set_exception_handler(static function DThrowable $exception): void {
    echo "\n";

    $cause = $exception;
    $root = true;

    while (null !== $cause) {
        if (!$root) {
            echo "Caused by\n";
        }

    public static function call(callable $function, mixed ...$arguments): mixed
    {
        set_error_handler(static function Dint $type, string $message, string $file, int $line) {
            if (__FILE__ === $file) {
                $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 3);
                $file = $trace[2]['file'] ?? $file;
                $line = $trace[2]['line'] ?? $line;
            }

            throw new \ErrorException($message, 0, $type$file$line);
        });

        try {
            return $function(...$arguments);
        } finally {
            restore_error_handler();
        }
    }

    public function __construct(BufferingLogger $bootstrappingLogger = null, bool $debug = false)
    {
        
$classes[] = sprintf("\$classes[] = %s;\n", var_export($item, true));
        }

        file_put_contents($filesprintf("\n\$classes = [];\n%s\$preloaded = Preloader::preload(\$classes, \$preloaded);\n", implode('', $classes)), \FILE_APPEND);
    }

    public static function preload(array $classes, array $preloaded = []): array
    {
        set_error_handler(function D$t$m$f$l) {
            if (error_reporting() & $t) {
                if (__FILE__ !== $f) {
                    throw new \ErrorException($m, 0, $t$f$l);
                }

                throw new \ReflectionException($m);
            }
        });

        $prev = [];

        try {
            while ($prev !== $classes) {
                $prev = $classes;
                
return $defaultCommands;
    }

    private function registerErrorHandler()
    {
        set_error_handler(function D$errno$errstr$errfile$errline) {
            // error was suppressed with the @-operator             if (error_reporting() === 0 || $errno === E_USER_DEPRECATED) {
                return false;
            }

            throw new ErrorException($errstr, 0, $errno$errfile$errline);
        });
    }
}
$unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
        try {
            $values = [];
            foreach (apcu_fetch($ids$ok) ?: [] as $k => $v) {
                if (null !== $v || $ok) {
                    $values[$k] = null !== $this->marshaller ? $this->marshaller->unmarshall($v) : $v;
                }
            }

            return $values;
        } catch (\Error $e) {
            throw new \ErrorException($e->getMessage()$e->getCode(), \E_ERROR, $e->getFile()$e->getLine());
        } finally {
            ini_set('unserialize_callback_func', $unserializeCallbackHandler);
        }
    }

    protected function doHave(string $id): bool
    {
        return apcu_exists($id);
    }

    protected function doClear(string $namespace): bool
    {
public static function createConnection(#[\SensitiveParameter] array|string $dsn, array $options = []): Bucket|Collection     {
        if (\is_string($dsn)) {
            $dsn = [$dsn];
        }

        if (!static::isSupported()) {
            throw new CacheException('Couchbase >= 3.0.0 < 4.0.0 is required.');
        }

        set_error_handler(static fn ($type$msg$file$line) => throw new \ErrorException($msg, 0, $type$file$line));

        $dsnPattern = '/^(?<protocol>couchbase(?:s)?)\:\/\/(?:(?<username>[^\:]+)\:(?<password>[^\@]{6,})@)?'
            .'(?<host>[^\:]+(?:\:\d+)?)(?:\/(?<bucketName>[^\/\?]+))(?:(?:\/(?<scopeName>[^\/]+))'
            .'(?:\/(?<collectionName>[^\/\?]+)))?(?:\/)?(?:\?(?<options>.*))?$/i';

        $newServers = [];
        $protocol = 'couchbase';
        try {
            $username = $options['username'] ?? '';
            $password = $options['password'] ?? '';

            
0,
            0,
        ];

        if (!class_exists(SilencedErrorContext::class)) {
            return;
        }

        yield 'logs with some deprecations' => [
            1,
            [
                ['message' => 'foo3', 'context' => ['exception' => new \ErrorException('warning', 0, \E_USER_WARNING)], 'priority' => 100, 'priorityName' => 'DEBUG'],
                ['message' => 'foo', 'context' => ['exception' => new \ErrorException('deprecated', 0, \E_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'],
                ['message' => 'foo2', 'context' => ['exception' => new \ErrorException('deprecated', 0, \E_USER_DEPRECATED)], 'priority' => 100, 'priorityName' => 'DEBUG'],
            ],
            [
                ['message' => 'foo3', 'context' => ['exception' => ['warning', \E_USER_WARNING]], 'priority' => 100, 'priorityName' => 'DEBUG'],
                ['message' => 'foo', 'context' => ['exception' => ['deprecated', \E_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false],
                ['message' => 'foo2', 'context' => ['exception' => ['deprecated', \E_USER_DEPRECATED]], 'priority' => 100, 'priorityName' => 'DEBUG', 'errorCount' => 1, 'scream' => false],
            ],
            2,
            0,
            [100 => ['count' => 3, 'name' => 'DEBUG']],
        ];
return $defaultCommands;
    }

    private function registerErrorHandler()
    {
        set_error_handler(function D$errno$errstr$errfile$errline) {
            // error was suppressed with the @-operator             if (error_reporting() === 0 || $errno === E_USER_DEPRECATED) {
                return false;
            }

            throw new ErrorException($errstr, 0, $errno$errfile$errline);
        });
    }
}
self::assertThat(self::getRequest()$constraint$message);
    }

    public static function assertThatForResponse(Constraint $constraint, string $message = ''): void
    {
        try {
            self::assertThat(self::getResponse()$constraint$message);
        } catch (ExpectationFailedException $exception) {
            if (($serverExceptionMessage = self::getResponse()->headers->get('X-Debug-Exception'))
                && ($serverExceptionFile = self::getResponse()->headers->get('X-Debug-Exception-File'))) {
                $serverExceptionFile = explode(':', $serverExceptionFile);
                $exception->__construct($exception->getMessage()$exception->getComparisonFailure()new \ErrorException(rawurldecode($serverExceptionMessage), 0, 1, rawurldecode($serverExceptionFile[0])$serverExceptionFile[1])$exception->getPrevious());
            }

            throw $exception;
        }
    }

    public static function assertThatForClient(Constraint $constraint, string $message = ''): void
    {
        self::assertThat(self::getClient()$constraint$message);
    }

    
case E_CORE_WARNING:
            case E_USER_WARNING:
            case E_ERROR:
            case E_USER_ERROR:
            case E_CORE_ERROR:
                break;
            case E_USER_DEPRECATED:
                $this->get('corelogger')->debug($errstr);
                break;
            case E_RECOVERABLE_ERROR:
                if ($this->throwOnRecoverableError) {
                    throw new ErrorException($this->_errorLevelList[$errno] . ': ' . $errstr, 0, $errno$errfile$errline);
                }
                break;
            default:
                throw new ErrorException($this->_errorLevelList[$errno] . ': ' . $errstr, 0, $errno$errfile$errline);
        }

        if (self::$_origErrorHandler !== null) {
            return \call_user_func(self::$_origErrorHandler$errno$errstr$errfile$errline);
        }

        return true;
    }
/** * Clones a PHP variable. * * @param int $filter A bit field of Caster::EXCLUDE_* constants */
    public function cloneVar(mixed $var, int $filter = 0): Data
    {
        $this->prevErrorHandler = set_error_handler(function D$type$msg$file$line$context = []) {
            if (\E_RECOVERABLE_ERROR === $type || \E_USER_ERROR === $type) {
                // Cloner never dies                 throw new \ErrorException($msg, 0, $type$file$line);
            }

            if ($this->prevErrorHandler) {
                return ($this->prevErrorHandler)($type$msg$file$line$context);
            }

            return false;
        });
        $this->filter = $filter;

        if ($gc = gc_enabled()) {
            
$classes[] = sprintf("\$classes[] = %s;\n", var_export($item, true));
        }

        file_put_contents($filesprintf("\n\$classes = [];\n%s\$preloaded = Preloader::preload(\$classes, \$preloaded);\n", implode('', $classes)), \FILE_APPEND);
    }

    public static function preload(array $classes, array $preloaded = []): array
    {
        set_error_handler(function D$t$m$f$l) {
            if (error_reporting() & $t) {
                if (__FILE__ !== $f) {
                    throw new \ErrorException($m, 0, $t$f$l);
                }

                throw new \ReflectionException($m);
            }
        });

        $prev = [];

        try {
            while ($prev !== $classes) {
                $prev = $classes;
                
if (false !== $value = unserialize($value)) {
                    return $value;
                }
            } elseif (false === $igbinaryNull) {
                throw new \RuntimeException('Failed to unserialize values, did you forget to install the "igbinary" extension?');
            } elseif (null !== $value = igbinary_unserialize($value)) {
                return $value;
            }

            throw new \DomainException(error_get_last() ? error_get_last()['message'] : 'Failed to unserialize values.');
        } catch (\Error $e) {
            throw new \ErrorException($e->getMessage()$e->getCode(), \E_ERROR, $e->getFile()$e->getLine());
        } finally {
            ini_set('unserialize_callback_func', $unserializeCallbackHandler);
        }
    }

    /** * @internal */
    public static function handleUnserializeCallback(string $class): never
    {
        throw new \DomainException('Class not found: '.$class);
    }
Home | Imprint | This part of the site doesn't use cookies.