public function handleError($model, $query, \PDOException $e) { // echo "*** Model in handleError: " . $model . "\n"; switch ($e->getCode()) { // MySQL table missing case '42S02': // SQLite table missing // SQLite table missing case 'HY000' && stripos($e->getMessage(), "no such table") !== false: if ($model != 'StdClass') { $instance = new $model(); if ($instance instanceof ActiveRecord) { $table_builder = new TableBuilder($instance); $table_builder->build(); return $this->query($query, $model); // Re-run the query } } throw new DatabaseLayer\TableDoesntExistException($e->getCode() . ": " . $e->getMessage()); default: // Write exception to log. if (DatabaseLayer::getInstance()->getLogger()) { DatabaseLayer::getInstance()->getLogger()->addError("Active Record Exception in " . $model . "\n\n" . $e->getCode() . ": " . $e->getMessage() . "\n\nrunning:\n\n{$query}"); } throw new DatabaseLayer\Exception($e->getCode() . ": " . $e->getMessage() . ".\n\n" . $query); } }
/** * Constructor. * * @param \PDOException $exception The PDO exception to wrap. */ public function __construct(\PDOException $exception) { parent::__construct($exception->getMessage(), 0, $exception->getPrevious()); $this->code = $exception->getCode(); $this->errorInfo = $exception->errorInfo; $this->errorCode = isset($exception->errorInfo[1]) ? $exception->errorInfo[1] : $exception->getCode(); $this->sqlState = isset($exception->errorInfo[0]) ? $exception->errorInfo[0] : $exception->getCode(); }
/** * @param \PDOException $exception * @return MySqlException */ public static function createFromPDOException(\PDOException $exception) { $message = $exception->getMessage(); $codePosition = strpos($message, "[{$exception->getCode()}]"); if ($codePosition !== false) { $message = trim(substr($message, $codePosition + strlen("[{$exception->getCode()}]") + 1)); } return new MySqlException($message, $exception->getCode()); }
/** * Throw DbException with query info * * @param string $sql * @param array $params * @param \PDOException $e * * @throws DbException */ protected function throwExceptionWithInfo($sql, array $params, \PDOException $e) { $exception = new DbException($e->getMessage(), (int) $e->getCode(), $e); $exception->setSql($sql); $exception->setParams($params); throw $exception; }
public function __construct(\PDOException $e, $extraMessage = '') { // Strip boring unnecessary info from error message $strippedMsg = preg_replace('/SQLSTATE\\[[A-Za-z-0-9]+\\]( \\[[A-Za-z-0-9]+\\])?:?\\s?/', '', $e->getMessage()); // PDOExceptions' getCode() can return a code with letters, which normal // exceptions won't accept. A converted code is better than no code at all though. parent::__construct($strippedMsg . $extraMessage, (int) $e->getCode()); }
/** * Create a new query excetion instance. * * @param string $sql * @param array $bindings * @param \PDOException $previous * @return void */ public function __construct($sql, array $bindings, $previous) { $this->sql = $sql; $this->bindings = $bindings; $this->previous = $previous; $this->code = $previous->getCode(); $this->errorInfo = $previous->errorInfo; $this->message = $this->formatMessage($sql, $bindings, $previous); }
/** * @param PDOException $exception */ public function throwException(PDOException $exception) { if ($this->debug) { echo '<pre>'; print_r(array($exception->getMessage(), $exception->getCode())); echo '</pre>'; die; } }
/** * @covers Veles\DataBase\Exceptions\DbException::__construct * * @param string $message * @param string $ansi_code * @param int $code * @param \PDOException $exception * * @dataProvider constructProvider */ public function testConstruct($message, $ansi_code, $code, $exception) { $obj = new DbException($exception->getMessage(), (int) $exception->getCode(), $exception); $result = $obj->getMessage(); $msg = 'Wrong DbException::__construct() behavior!'; $this->assertSame($message, $result, $msg); $result = $obj->getAnsiCode(); $msg = 'Wrong DbException::__construct() behavior!'; $this->assertSame($ansi_code, $result, $msg); $result = $obj->getCode(); $msg = 'Wrong DbException::__construct() behavior!'; $this->assertSame($code, $result, $msg); }
/** * Run RAW Query * * @param string $sql * * @return Zend_Db_Statement_Interface * @throws PDOException */ public function raw_query($sql) { try { return $this->query($sql); } catch (Zend_Db_Statement_Exception $e) { // Convert to PDOException to maintain backwards compatibility with usage of MySQL adapter $e = $e->getPrevious(); if (!$e instanceof PDOException) { $e = new PDOException($e->getMessage(), $e->getCode()); } throw $e; } }
/** * Constructor. * * @param \PDOException $e */ public function __construct(\PDOException $e) { if (strstr($e->getMessage(), 'SQLSTATE[')) { preg_match('/SQLSTATE\\[(\\w+)\\] \\[(\\w+)\\] (.*)/', $e->getMessage(), $matches); if (count($matches)) { $this->code = $matches[1] == 'HT000' ? $matches[2] : $matches[1]; $this->message = $matches[3]; } else { $this->code = $e->getCode(); $this->message = $e->getMessage(); } } }
public function handlePDOException(PDOException $e) { trigger_error('PHP PDO Error in ' . $e->getFile() . ' @' . strval($e->getLine()) . ' [' . strval($e->getCode()) . '] :: ' . $e->getMessage(), E_USER_WARNING); foreach ($e->getTrace() as $a => $b) { foreach ($b as $c => $d) { if ($c == 'args') { foreach ($d as $e => $f) { trigger_error('PHP PDO Error trace: ' . strval($a) . '# args: ' . $e . ': ' . $f . '', E_USER_WARNING); } } else { trigger_error('PHP PDO Error trace: ' . strval($a) . '# ' . $c . ': ' . $d . '', E_USER_WARNING); } } } }
/** * Constructor * * @param \PDOException $e PDO exception * @param string $query SQL query OPTIONAL * @param array $params SQL query parameters OPTIONAL * * @return void */ public function __construct(\PDOException $e, $query = null, array $params = array()) { $code = $e->getCode(); $message = $e->getMessage(); // Remove user credentials if (strstr($message, 'SQLSTATE[') && preg_match('/SQLSTATE\\[(\\w+)\\] \\[(\\w+)\\] (.*)/', $message, $matches)) { $code = 'HT000' == $matches[1] ? $matches[2] : $matches[1]; $message = $matches[3]; } // Add additional information if ($query) { $message .= PHP_EOL . 'SQL query: ' . $query; } if ($params) { $message .= PHP_EOL . 'SQL query parameters: ' . var_export($params, true); } $this->code = intval($code); $this->message = $message; }
/** * Writes a ditailed error message to the log file, if specified. * * @param \PDOException $e * @param string $strMessage * @param string $strSql * @return void */ private function generateError(\PDOException $e, $strMessage, $strSql = '') { $strError = PHP_EOL . "\t-- " . $strMessage . PHP_EOL . "\t-- PDOException code: " . $e->getCode() . PHP_EOL . "\t-- File: " . $e->getFile() . PHP_EOL . "\t-- Line: " . $e->getLine() . PHP_EOL . "\t-- Message: " . $e->getMessage() . (empty($strSql) ? '' : PHP_EOL . "\t-- SQL: " . $strSql . PHP_EOL) . PHP_EOL . "\t-------------------------------------------------------" . PHP_EOL . PHP_EOL; $this->log($strError, true); if (!empty($this->strWriteErrorLogTo)) { if (is_resource($this->resourceErrorLog)) { fwrite($this->resourceErrorLog, $strError); } else { $this->resourceErrorLog = fopen($this->strWriteErrorLogTo, 'a'); if (is_resource($this->resourceErrorLog)) { fwrite($this->resourceErrorLog, $strError); } } } unset($strError); }
/** * @link http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html */ protected function convertPostgresException(\PDOException $e, \Exception $root) { $state = (string) isset($e->errorInfo[0]) ? $e->errorInfo[0] : $e->getCode(); switch ($state) { case '0A000': if (strpos($e->getMessage(), 'truncate') !== false) { return new ForeignKeyConstraintViolationException($root->getMessage(), 0, $root); } break; case '23503': return new ForeignKeyConstraintViolationException($root->getMessage(), 0, $root); case '23505': return new UniqueConstraintViolationException($root->getMessage(), 0, $root); } return new DatabaseException($root->getMessage(), 0, $root); }
/** * 抛出错误信息 * * @param PDOException $e */ private function db_error(PDOException $e) { echo '出错了!!!<br />'; echo '错误文件:', $e->getFile(), '<br />'; echo '错误行号:', $e->getLine(), '<br />'; echo '错误编码:', $e->getCode(), '<br />'; echo '错误详情:', $e->getMessage(), '<br />'; exit('END...'); }
/** * @param \PDOException $exception * @return bool */ public static function isUnknownDatabase(\PDOException $exception) { return $exception->getCode() == self::ER_BAD_DB_ERROR_1 || $exception->getCode() == self::ER_BAD_DB_ERROR_2 && preg_match('/SQLSTATE\\[42000\\].*\\s1049\\s/', $exception->getMessage()) != false; }
/** * Parses PDO exception message and returns its components and status * * @param PDOException $e PDO Exception * @param string $err_code Output error code parameter * @param string $err_message Output error message parameter * @return bool TRUE for error cases, FALSE for notifications and warnings */ private function _parseError(PDOException $e, &$err_code, &$err_message) { $pdo_message = $e->getMessage(); if (preg_match('#SQLSTATE\\[(\\w+)\\].*?: (.*)#', $pdo_message, $matches)) { $err_code = $matches[1]; $err_message = $matches[2]; } else { $err_code = $e->getCode(); $err_message = $pdo_message; } return $err_code > '02'; }
/** * Run RAW Query * * @param string $sql * @return Zend_Db_Statement_Interface * @throws PDOException */ public function raw_query($sql) { $lostConnectionMessage = 'SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query'; $tries = 0; do { $retry = false; try { $result = $this->query($sql); } catch (Exception $e) { // Convert to PDOException to maintain backwards compatibility with usage of MySQL adapter if ($e instanceof Zend_Db_Statement_Exception) { $e = $e->getPrevious(); if (!$e instanceof PDOException) { $e = new PDOException($e->getMessage(), $e->getCode()); } } // Check to reconnect if ($tries < 10 && $e->getMessage() == $lostConnectionMessage) { $retry = true; $tries++; } else { throw $e; } } } while ($retry); return $result; }
/** * display a nice error if it occurs and log everything * * @param PDOException $error * @param bool $showerror if set to false, the error will be logged but we go on */ private static function _showerror($error, $showerror = true) { global $userinfo, $theme, $linker; /** * log to a file, so we can actually ask people for the error * (no one seems to find the stuff in the syslog) */ $sl_dir = makeCorrectDir(FROXLOR_INSTALL_DIR . "/logs/"); if (!file_exists($sl_dir)) { @mkdir($sl_dir, 0755); } $sl_file = makeCorrectFile($sl_dir . "/sql-error.log"); $sqllog = @fopen($sl_file, 'a'); @fwrite($sqllog, date('d.m.Y H:i', time()) . " --- " . str_replace("\n", " ", $error->getMessage()) . "\n"); @fwrite($sqllog, date('d.m.Y H:i', time()) . " --- DEBUG: \n" . $error->getTraceAsString() . "\n"); @fclose($sqllog); /** * log error for reporting */ $errid = substr(md5(microtime()), 5, 5); $err_file = makeCorrectFile($sl_dir . "/" . $errid . "_sql-error.log"); $errlog = @fopen($err_file, 'w'); @fwrite($errlog, "|CODE " . $error->getCode() . "\n"); @fwrite($errlog, "|MSG " . $error->getMessage() . "\n"); @fwrite($errlog, "|FILE " . $error->getFile() . "\n"); @fwrite($errlog, "|LINE " . $error->getLine() . "\n"); @fwrite($errlog, "|TRACE\n" . $error->getTraceAsString() . "\n"); @fclose($errlog); if ($showerror) { // include userdata.inc.php require FROXLOR_INSTALL_DIR . "/lib/userdata.inc.php"; // fallback $theme = 'Sparkle'; // le format if (isset($sql['root_user']) && isset($sql['root_password']) && (!isset($sql_root) || !is_array($sql_root))) { $sql_root = array(0 => array('caption' => 'Default', 'host' => $sql['host'], 'socket' => isset($sql['socket']) ? $sql['socket'] : null, 'user' => $sql['root_user'], 'password' => $sql['root_password'])); } // hide username/password in messages $error_message = $error->getMessage(); $error_trace = $error->getTraceAsString(); // error-message $error_message = str_replace($sql['password'], 'DB_UNPRIV_PWD', $error_message); $error_message = str_replace($sql_root[0]['password'], 'DB_ROOT_PWD', $error_message); // error-trace $error_trace = str_replace($sql['password'], 'DB_UNPRIV_PWD', $error_trace); $error_trace = str_replace($sql_root[0]['password'], 'DB_ROOT_PWD', $error_trace); if ($error->getCode() == 2003) { $error_message = "Unable to connect to database. Either the mysql-server is not running or your user/password is wrong."; $error_trace = ""; } // clean up sensitive data unset($sql); unset($sql_root); if (isset($theme) && $theme != '' && !isset($_SERVER['SHELL']) || isset($_SERVER['SHELL']) && $_SERVER['SHELL'] == '') { // if we're not on the shell, output a nice error $_errtpl = dirname($sl_dir) . '/templates/' . $theme . '/misc/dberrornice.tpl'; if (file_exists($_errtpl)) { $err_hint = file_get_contents($_errtpl); // replace values $err_hint = str_replace("<TEXT>", $error_message, $err_hint); $err_hint = str_replace("<DEBUG>", $error_trace, $err_hint); $err_hint = str_replace("<CURRENT_YEAR>", date('Y', time()), $err_hint); $err_report_html = ''; if (is_array($userinfo) && ($userinfo['adminsession'] == '1' && Settings::Get('system.allow_error_report_admin') == '1' || $userinfo['adminsession'] == '0' && Settings::Get('system.allow_error_report_customer') == '1')) { $err_report_html = '<a href="<LINK>" title="Click here to report error">Report error</a>'; $err_report_html = str_replace("<LINK>", $linker->getLink(array('section' => 'index', 'page' => 'send_error_report', 'errorid' => $errid)), $err_report_html); } $err_hint = str_replace("<REPORT>", $err_report_html, $err_hint); // show die($err_hint); } } die("We are sorry, but a MySQL - error occurred. The administrator may find more information in in the sql-error.log in the logs/ directory"); } }
/** * 修正错误 * * @param \PDOException $e */ private function processError(\PDOException $e) { if ($this->retryTimes >= 3) { throw $e; return; } switch ($e->getCode()) { case '7': //数据库不存在 $creator = new database\Schema(static::$module, $this->conn); $creator->createDataBase(); case '42P01': $creator = new database\Schema(static::$module, $this->conn); $creator->createTable($this->table, static::$columns); break; default: throw $e; return; } $this->retryTimes++; }
/** * Returns comprehensive information about the given error. * * @param PDOException $e * @return string */ protected function generateError(PDOException $e) { return '<table border = "1">' . '<tr><td>Err code</td><td>' . $e->getCode() . '</td></tr>' . '<tr><td>In file </td><td>' . $e->getFile() . '</td></tr>' . '<tr><td>In line </td><td>' . $e->getLine() . '</td></tr>' . '<tr><td>Details </td><td>' . $e->getMessage() . '</td></tr></table>'; }
/** * @param \PDOException $exception * @return static */ public static function createFromException(\PDOException $exception) { $newSelf = new static($exception->getMessage(), 0, $exception); $newSelf->code = $exception->getCode(); return $newSelf; }
/** * Run RAW Query * * @param string $sql * @return StatementInterface * @throws \PDOException */ public function rawQuery($sql) { try { $result = $this->query($sql); } catch (InvalidArgumentException $e) { // Convert to \PDOException to maintain backwards compatibility with usage of MySQL adapter $e = $e->getPrevious(); if (!$e instanceof \PDOException) { $e = new \PDOException($e->getMessage(), $e->getCode()); } throw $e; } return $result; }
/** * Обработка исключений * * @param Repository $repository * @param \PDOException $exception */ protected function resolveException(Repository $repository, \PDOException $exception) { if ($exception->getCode() == '42S02') { // Table doesn't exist $this->create($repository); } elseif ($exception->getCode() == '42S22') { // Column not found $this->diff($repository); } else { throw $exception; } throw new \PDOException($repository->getEntityName() . ' Произошла ошибка, но она исправлена. Попробуйте повторить операцию', 0, $exception); }
public function __construct(PDOException $e) { if (method_exists($this, $method = 'code' . $e->getCode())) { return call_user_func_array(array($this, $method), array($e)); } else { die($e->getMessage()); } }
public static function handle(PDOException $pdoExc) { throw new API_DB_Exception($pdoExc->getMessage(), $pdoExc->getCode()); }
/** * Catch duplicate key error * * @param \PDOException $e * @param \PDOStatement $stmt * @return string */ private function catchDuplicateKeyError(\PDOException $e, \PDOStatement $stmt) { if (0 === strpos($e->getCode(), '23')) { $stmt->execute(); return $stmt->rowCount() ? $this->getResult($stmt) : ''; } throw $e; }
function opdErrorHandler(PDOException $exc) { echo '<br/><b>Open Power Driver internal error #' . $exc->getCode() . ': </b> ' . $exc->getMessage() . '<br/> Query used: <i>' . opdClass::$lastQuery . '</i><br/>'; }
/** * Wraps and re-throws any PDO exception thrown by static::query(). * * @param \PDOException $e * The exception thrown by static::query(). * @param $query * The query executed by static::query(). * @param array $args * An array of arguments for the prepared statement. * @param array $options * An associative array of options to control how the query is run. * * @return \Drupal\Core\Database\StatementInterface|int|null * Most database drivers will return NULL when a PDO exception is thrown for * a query, but some of them may need to re-run the query, so they can also * return a \Drupal\Core\Database\StatementInterface object or an integer. * * @throws \Drupal\Core\Database\DatabaseExceptionWrapper * @throws \Drupal\Core\Database\IntegrityConstraintViolationException */ protected function handleQueryException(\PDOException $e, $query, array $args = array(), $options = array()) { if ($options['throw_exception']) { // Wrap the exception in another exception, because PHP does not allow // overriding Exception::getMessage(). Its message is the extra database // debug information. $query_string = $query instanceof StatementInterface ? $query->getQueryString() : $query; $message = $e->getMessage() . ": " . $query_string . "; " . print_r($args, TRUE); // Match all SQLSTATE 23xxx errors. if (substr($e->getCode(), -6, -3) == '23') { $exception = new IntegrityConstraintViolationException($message, $e->getCode(), $e); } else { $exception = new DatabaseExceptionWrapper($message, 0, $e); } throw $exception; } return NULL; }
/** * @param \PDOException $e * @return bool */ private function isConcurrencyException(\PDOException $e) { return $e->getCode() === "23000" && strpos($e->getMessage(), self::VERSION_AGGREGATE_ID_KEY_NAME); }