Handle an exception that occurred during connect execution.

@param \Exception $e
@param string     $dsn
@param string     $username
@param string     $password
@param array      $options

@throws \Exception

@return \PDO
501960
protected function tryAgainIfCausedByLostConnection(Exception $e, $dsn, $username, $password, $options)
    {
        if ($this->causedByLostConnection($e)) {
            return $this->createPdoConnection($dsn, $username, $password, $options);
        }

        throw $e;
    }
499285
public function createConnection($dsn, array $config, array $options)
    {
        [$username, $password] = [
            $config['username'] ?? null, $config['password'] ?? null,
        ];

        try {
            return $this->createPdoConnection(
                $dsn, $username, $password, $options
            );
        } catch (Exception $e) {
            return $this->tryAgainIfCausedByLostConnection(
                $e, $dsn, $username, $password, $options
            );
        }
    }
948537
public function connect($debug = false)
    {
        if (isset($this->options['dsn'])) {
            if ($this->options['verbose']) {
                echo "<p>Connecting to dsn:<br><code>" . $this->options['dsn'] . "</code>";
            }

            try {
                $this->db = new \PDO(
                    $this->options['dsn'],
                    $this->options['username'],
                    $this->options['password'],
                    $this->options['driver_options']
                );

                $this->db->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, $this->options['fetch_mode']);
                $this->db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);

            } catch(\Exception $e) {

                if ($debug || $this->options['debug_connect']) {
                    // For debug purpose, shows all connection details
                    throw $e;
                } else {
                    // Hide connection details.
                    throw new \PDOException("Could not connect to database, hiding connection details. Connect using 'debug' to see the full exception message.");
                }
            }

        } else {
            throw new \Exception("You can not connect, missing dsn.");
        }

        $this->loadHistory();
    }
823946
public function setDriver($dsn, array $config = [], array $options = [])
    {
        $class = '\Micro\Db\Drivers\\'.ucfirst(substr($dsn, 0, strpos($dsn, ':'))).'Driver';

        if (!class_exists($class)) {
            throw new Exception('DB driver `'.$class.'` not supported');
        }

        unset($this->driver);

        $this->driver = new $class($dsn, $config, $options);
    }
1072807
protected function createPdoConnection($dsn, $username, $password, $options)
    {
        return new PDO($dsn, $username, $password, $options);
    }
1297902
private function handleException($e)
    {
        // TODO: test coverage
        if ($e instanceof ClientException) {
            // will catch all 4xx errors
            if ($e->getResponse()->getStatusCode() == 403) {
                throw new AuthenticationException(
                    $this->apiKey,
                    $this->apiSecret,
                    null,
                    $e
                );
            } else {
                throw new DomainException(
                    'The OpenTok API request failed: '. json_decode($e->getResponse()->getBody(true))->message,
                    null,
                    $e
                );
            }
        } else if ($e instanceof ServerException) {
            // will catch all 5xx errors
            throw new UnexpectedValueException(
                'The OpenTok API server responded with an error: ' . json_decode($e->getResponse()->getBody(true))->message,
                null,
                $e
            );
        } else {
            // TODO: check if this works because Exception is an interface not a class
            throw new \Exception('An unexpected error occurred');
        }
    }
524884
protected function main(Options $options)
    {
        $this->debug('This is a debug message');
        $this->info('This is a info message');
        $this->notice('This is a notice message');
        $this->success('This is a success message');
        $this->warning('This is a warning message');
        $this->error('This is a error message');
        $this->critical('This is a critical message');
        $this->alert('This is a alert message');
        $this->emergency('This is a emergency message');
        throw new \Exception('Exception will be caught, too');
    }
1039640
public function exception(\Exception $e, array $options = [])
    {
        $message = $this->createExceptionMessages($e);
        return $this->message($message);
    }
576808
public function connect($dieOnError = false)
	{
		// Data Source String
		$dsn = $this->driver . ":dbname=" . $this->schema . ";host=" . $this->host . ";port=" . $this->port;

		// Attempt to make connection
		try
		{
			// '@' suppresses errors from this function. We output our own message if there's a problem
			@parent::__construct($dsn, $this->user, $this->pass);
		}
		catch(\PDOException $err)
		{
			if($dieOnError)
			{
				die("Unable to connect to the database server. Details: " . $err->getMessage() . ".");
			}
			else
			{
				\Thinker\Framework\Notification::push("Failed to connect to database '" . $this->schema . "'. Details: " . $err->getMessage(), 'error');
			}

			return false;
		}

		return true;
	}
360160
public static function connect($dsn)
    {
        $db = MDB2::connect($dsn);

        if (PEAR::isError($db)) {
            throw new SwatDBException($db);
        }

        return $db;
    }
852467
private function _buildConnection(Dsn $dsn)
    {
        if (isset($this->_drivers[$dsn->scheme])) {
            $driver = $this->_drivers[$dsn->scheme];

            return is_string($driver)
                ? new $driver($dsn) : call_user_func($driver, $dsn);
        }

        // check built in drivers
        switch ($dsn->scheme) {
            case 'mysql':
            case 'mysqli':
                return new Mysqli\Connection($dsn);
        }

        throw new \Pheasant\Exception("Unknown driver $driver");
    }
144063
public static function setDSN($dsn)
        {
            $dsn_details = parse_url($dsn);
            if (!is_array($dsn_details) || !array_key_exists('scheme', $dsn_details)) {
                throw new Exception('This does not look like a valid DSN - cannot read the database type');
            }
            try {
                self::setDriver($dsn_details['scheme']);
                $details = explode(';', $dsn_details['path']);
                foreach ($details as $detail) {
                    $detail_info = explode('=', $detail);
                    if (count($detail_info) != 2) {
                        throw new Exception('This does not look like a valid DSN - cannot read the connection details');
                    }
                    switch ($detail_info[0]) {
                        case 'host':
                            self::setHostname($detail_info[1]);
                            break;
                        case 'port':
                            self::setPort($detail_info[1]);
                            break;
                        case 'dbname':
                            self::setDatabaseName($detail_info[1]);
                            break;
                    }
                }
            } catch (\Exception $e) {
                throw $e;
            }
            self::$dsn = $dsn;
        }
1074978
public function setOption($option, $value)
    {
        if (! (@ldap_set_option($this->connection, $option, $value))) {
            $code = @ldap_errno($this->connection);
            throw new OptionException(
                sprintf(
                    'Could not change option %s value: Ldap Error Code=%s - %s',
                    $code,
                    ldap_err2str($code)
                )
            );
        }
    }
146169
public function createConnection($dsn, array $config, array $options)
    {
        $username = array_get($config, 'username');

        $password = array_get($config, 'password');

        return new PDO($dsn, $username, $password, $options);
    }
984161
public function connectOauth2($options)
    {
        $token = false;

        // source oauth provider
        $oauthProvider = $this->getProvider();

        // error
        if(\Craft\craft()->request->getParam('error'))
        {
            throw new \Exception("An error occured: ".\Craft\craft()->request->getParam('error'));
        }

        $state = \Craft\craft()->request->getParam('state');
        $code = \Craft\craft()->request->getParam('code');
        $oauth2state = \Craft\craft()->httpSession->get('oauth2state');

        if (is_null($code))
        {
            $authorizationOptions = $options['authorizationOptions'];

            if(count($options['scope']) > 0)
            {
                $authorizationOptions['scope'] = $options['scope'];
            }

            $authorizationUrl = $oauthProvider->getAuthorizationUrl($authorizationOptions);

            $state = $oauthProvider->getState();

            \Craft\craft()->httpSession->add('oauth2state', $state);

            OauthPlugin::log('OAuth 2.0 Connect - Redirect to the authorization URL'."\r\n".
	            "authorizationUrl: ".$authorizationUrl."\r\n".
	            "oauth2state: ".\Craft\craft()->httpSession->get('oauth2state')
	        , LogLevel::Info);

            \Craft\craft()->request->redirect($authorizationUrl);
        }
        elseif (!$state || $state !== $oauth2state)
        {
            OauthPlugin::log('OAuth 2.0 Connect - Invalid State'."\r\n".print_r([
                'state' => $state,
                'oauth2state' => $oauth2state,
            ], true), LogLevel::Info);

            \Craft\craft()->httpSession->remove('oauth2state');

            throw new \Exception("Invalid state");

        }
        else
        {
            OauthPlugin::log('OAuth 2.0 Connect - Authorization code retrieved: '.$code, LogLevel::Info);

            $token = $oauthProvider->getAccessToken('authorization_code', [
                'code' => $code
            ]);

            OauthPlugin::log("OAuth 2.0 Connect - Get Access Token\r\n".
	            "Access token: \r\n".
	            print_r($token, true)
	        , LogLevel::Info);
        }

        return $token;
    }
943515
public static function create(
        string $dsn,
        string $username = null,
        string $password = null,
        array $options = []
    ): EasyDB {
        return static::fromArray([$dsn, $username, $password, $options]);
    }
750887
public function onError(ConnectionInterface $conn, \Exception $e) {

        try {
            throw new \Exception($e->getMessage());
        }
        catch(\Exception $e) {
            throw new SocketServiceException(Messenger::error($e->getMessage()));
        }
        finally {
            $conn->close();
        }
    }