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 .
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!