Convert php errors to exceptions

@throws \RuntimeException
320715
public static function errorToException($errno, $errstr, $errfile, $errline)
    {
        $exclude = E_STRICT | E_NOTICE | E_USER_NOTICE;
        if (((error_reporting() & $errno) != $errno) || (($exclude & $errno) == $errno)) {
            return false;
        }

        $constants = get_defined_constants(true);
        $name = 'Unknown PHP Error (' . $errno . ')';
        foreach ($constants['Core'] as $c => $value) {
            if ((substr($c, 0, 2) != 'E_') || ($value != $errno)) {
                continue;
            }

            $name = 'PHP ' . ucwords(str_replace('_', ' ', strtolower(substr($c, 2))));
        }

        $exception = new \RuntimeException(sprintf('%s: %s in %s on line %d', $name, $errstr, $errfile, $errline), $errno);

        // Impossible to throw an exception without stack trace
        // happens when errors occour in shutdown scope (i.e. serialize handler)
        if (count($exception->getTrace()) < 1) {
            return false;
        }

        throw $exception;
    }
1037637
protected function handleJsonError()
    {
        if (function_exists('json_last_error_msg') && json_last_error() !== JSON_ERROR_NONE) {
            // PHP >= 5.5.0
            $message = json_last_error_msg();

        } elseif (function_exists('json_last_error')) {
            // PHP >= 5.3.0
            switch (json_last_error()) {
                case JSON_ERROR_NONE:
                    break;
                case JSON_ERROR_DEPTH:
                    $message = 'maximum stack depth exceeded';
                    break;
                case JSON_ERROR_STATE_MISMATCH:
                    $message = 'underflow or the modes mismatch';
                    break;
                case JSON_ERROR_CTRL_CHAR:
                    $message = 'unexpected control character found';
                    break;
                case JSON_ERROR_SYNTAX:
                    $message = 'malformed JSON';
                    break;
                case JSON_ERROR_UTF8:
                    $message = 'malformed UTF-8 characters, possibly ' .
                        'incorrectly encoded';
                    break;
                default:
                    $message = 'unknown error';
                    break;
            }
        }

        if (isset($message)) {
            throw new \RuntimeException('Error encoding/decoding JSON: ' . $message);
        }
    }
810319
private function runAddedExceptions()
    {
        if (!empty($this->addedExceptions)) {
            foreach ($this->addedExceptions as $exception => $message) {
                throw new $exception($message);
                break;
            }
        }
    }
1047083
protected function setErrorHandlers()
  {
    # Report all PHP errors (see changelog)
    $this->errorLevel = \error_reporting( E_ALL | E_STRICT);

    # set to the user defined error handler
    $old_error_handler = \set_error_handler(array($this,'errorHandler'), E_ALL);
    $old_exception_handler = \set_exception_handler(array($this,'exceptionHandler'));

    $this->getLogger()->debug('Error handlers set');

    return true;
  }
993296
public function json()
    {
        $json = json_decode($this->getBody(), true);
        if ($json === null) {
            throw new RuntimeException(sprintf(
                "Can't decode response as JSON: %s",
                function_exists('json_last_error_msg')?
                    json_last_error_msg():
                    'Error code '.json_last_error()
            ));
        }
        return $json;
    }
461052
private function constructException()
    {
        $this->details['argument_type_error'][$this->argument] = $this->details['argument_type_error']['ARG'];
        $this->details['argument_type_error'][$this->argument] = str_replace(['VAR_TYPE', 'ARG_TYPE'], [$this->argumentValueType, $this->argumentType], $this->details['argument_type_error'][$this->argument]);
        unset($this->details['argument_type_error']['ARG']);

        $this->resolution = str_replace('ARG_TYPE', $this->argumentType, $this->resolution);
    }
849979
private function insertErrorMessages() {

		$rex = '/\{(?:\w+\|)*error_%s(?:\|\w+)*:([^\}]+)\}/i';

		foreach($this->formErrors as $name => $v) {
			if(!is_array($v)) {
				$this->html = preg_replace(
					sprintf($rex, $name),
					'$1',
					$this->html
				);
			}
			else {
				foreach(array_keys($this->formErrors[$name]) as $ndx) {
					$this->html = preg_replace(
						sprintf($rex, $name),
						empty($this->formErrors[$name][$ndx]) ? '' : '$1',
						$this->html,
						1
					);
				}
			}
		}
		
		return $this;

	}
952776
public function showError($msg = null)
    {
        $errorMessage = null;
        $code = null;
        if ((null === $code) && (null === $msg)) {
            $errorCode = $this->connection->errorCode();
            $errorInfo = $this->connection->errorInfo();
        } else {
            $errorCode = $code;
            $errorInfo = $msg;
        }
    
        if (is_array($errorInfo)) {
            $errorMessage = null;
            if (isset($errorInfo[1])) {
                $errorMessage .= $errorInfo[1];
            }
            if (isset($errorInfo[2])) {
                $errorMessage .= ' : ' . $errorInfo[2];
            }
        } else {
            $errorMessage = $errorInfo;
        }
        throw new Exception('Error: ' . $errorCode . ' => ' . $errorMessage  . '.');
    }
1285722
public function PHPExceptionHandler($exception)
    {
        session_write_close();
        $message = $exception->getMessage() . ' | File: {file} | Ln: {line} | ST: {stacktrace}';
        $context = array(
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'stacktrace' => $exception->getTraceAsString()
        );
        $this->logger->log($this->exceptionLogLevel, $message, $context);
    }
412295
private function error(): void
    {
        $code = socket_last_error($this->socket);
        $msg  = socket_strerror($code);
        throw new \RuntimeException($msg, $code);

    }
801999
public function func()
    {
        $args = func_get_args();
        $fns  = explode('|', array_shift($args));
        $res  = null;

        foreach (array_reverse($fns) as $fnc) {
            if (!isset($this->functions[$fnc])) {
                throw new \RuntimeException(sprintf('Template function "%s" does not exist.', $fnc));
            }

            $res = $this->functions[$fnc]->call($args);

            if (!$this->functions[$fnc]->getOption('is_safe_html')) {
                $res = $this->escape($res);
            }

            $args = [$res];
        }

        return $res;
    }
433334
public static function error(string $str)
    {
        // Reloads current page with the same error, prevent endless loop
        if (SELF === REF) {
            throw new \RuntimeException('Looping references');
        }

        if (IS_AJAX_REQUEST) {
            // Return as string for ajax response
            echo $str;
        } else {
            // Run as Javascript alert
            ?>
            <script type="text/javascript">alert('<?= $str ?>');
                if (history.length) {
                    // Go back
                    history.back();
                }
                // Reload page
                window.location = '<?= REF ?>'
            </script>
            <?php
        }
        exit;
    }
870008
private function convertException($rawException = null)
    {
        if (null === $rawException || $rawException instanceof ClientAware) {
            return $rawException;
        }

        $errorClass = $this->findErrorClass($rawException);
        if (null !== $errorClass) {
            return new $errorClass($rawException->getMessage(), $rawException->getCode(), $rawException);
        }

        return $rawException;
    }
776067
public function execute()
    {
        $statement = $this->getPdoStatement();
        $result = $statement->execute($this->bindings);
        if (!$result) {
            $errorInfo = $statement->errorInfo();
            throw new RuntimeException(
                $errorInfo[1],
                $errorInfo[2]
            );
        }
        return $statement;
    }
766251
public function validateForm()
    {
        $validator = $this->getValidationFactory()->make(
            $this->requestData(),
            $this->rules()
        );

        if ($validator->fails())
            throw new \Exception($this->formatErrors($validator->errors()));
    }
286402
public static function create($code = 500, array $context = [], $previous = null)
	{
		if (!isset(Response::$phrases[$code])) {
			throw new \RuntimeException("Http error not valid ({$code})");
		}

		$exception = new static(Response::$phrases[$code], $code, $previous);
		$exception->setContext($context);

		return $exception;
	}
734861
public static function processPcreError()
        {
            if (preg_last_error() != PREG_NO_ERROR) {
                switch (preg_last_error()) {
                    case PREG_INTERNAL_ERROR:
                        throw new Exception('PCRE PREG internal error');
                    case PREG_BACKTRACK_LIMIT_ERROR:
                        throw new Exception('PCRE PREG Backtrack limit error');
                    case PREG_RECURSION_LIMIT_ERROR:
                        throw new Exception('PCRE PREG Recursion limit error');
                    case PREG_BAD_UTF8_ERROR:
                        throw new Exception('PCRE PREG Bad UTF-8 error');
                    case PREG_BAD_UTF8_OFFSET_ERROR:
                        throw new Exception('PCRE PREG Bad UTF-8 offset error');
                }
            }
        }