Home > Database > Mysql Tutorial > larval how to catch mysql errors

larval how to catch mysql errors

藏色散人
Release: 2020-11-06 17:42:08
Original
2345 people have browsed it

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);
}
Copy after login

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..
    // ....
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template