larval 如何捕获mysql错误

larval 如何捕获mysql错误,第1张

larval 如何捕获mysql错误

larval捕获mysql错误的方法:1、使用errorInfo变量返回SQLSTATE错误和消息;2、使用异常处理程序“app/Exceptions/Handler.php并侦听QueryExceptions”将所有SQL错误记录到数据。

推荐:《mysql视频教程》

Laravel使用PDO,因此您可以使用errorInfo变量返回SQLSTATE错误和消息。基本上,您需要使用$e->errorInfo;

如果要将所有SQL错误记录到数据库中,可以使用异常处理程序(app/Exceptions/Handler.php并侦听QueryExceptions。像这样的:

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);
}

然后你可以用这样的东西:

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..
    // ....
}

以上就是larval 如何捕获mysql错误的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/704357.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-23
下一篇 2022-04-23

发表评论

登录后才能评论

评论列表(0条)

保存