How larval catches mysql errors: 1. Use the errorInfo variable to return SQLSTATE errors and messages; 2. Use the exception handler “app/Exceptions/Handler.php and listen to QueryExceptions” to log all SQL errors to the data .
Recommendation: “Mysql Video Tutorial”
Laravel uses PDO, so you can use the errorInfo variable to return SQLSTATE errors and messages. 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 The:
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 how larval catches mysql errors. For more information, please pay attention to other related articles on 1024programmer.com!