Home>Article>Database> larval how to catch mysql errors

larval how to catch mysql errors

藏色散人
藏色散人 Original
2020-11-06 10:01:50 2229browse

larval method to capture mysql errors: 1. Use the errorInfo variable to return SQLSTATE errors and messages; 2. Use the exception handler "app/Exceptions/Handler.php and listen for QueryExceptions" to log all SQL errors to the data .

larval how to catch mysql errors

Recommended: "mysql video tutorial"

Laravel uses PDO, so you can use the errorInfo variable to return SQLSTATE errors and news. Basically, you need to use $e->errorInfo;

If you want to log all SQL errors to the database, you can use an exception handler (app/Exceptions/Handler.php and listen for QueryExceptions. Like this of:

public function render($request, Exception $e) { switch ($e) { case ($e instanceof \Illuminate\Database\QueryException): LogTracker::saveSqlError($e); break; default: LogTracker::saveError($e, $e->getCode()); } return parent::render($request, $e); }

Then you can use something like this:

public function saveSqlError($exception) { $sql = $exception->getSql(); $bindings = $exception->getBindings() // Process the query's SQL and parameters and create the exact query foreach ($bindings as $i => $binding) { if ($binding instanceof \DateTime) { $bindings[$i] = $binding->format('\'Y-m-d H:i:s\''); } else { if (is_string($binding)) { $bindings[$i] = "'$binding'"; } } } $query = str_replace(array('%', '?'), array('%%', '%s'), $sql); $query = vsprintf($query, $bindings); // Here's the part you need $errorInfo = $exception->errorInfo; $data = [ 'sql' => $query, 'message' => isset($errorInfo[2]) ? $errorInfo[2] : '', 'sql_state' => $errorInfo[0], 'error_code' => $errorInfo[1] ]; // Now store the error into database, if you want.. // .... }

The above is the detailed content of larval how to catch mysql errors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn