1024programmer Mysql How does larval catch mysql errors

How does larval catch mysql errors

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!

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/how-does-larval-catch-mysql-errors/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索