【问题标题】:How to capture MySQL Error codes and Messages using Laravel 5.2?如何使用 Laravel 5.2 捕获 MySQL 错误代码和消息?
【发布时间】:2016-07-12 17:05:34
【问题描述】:

我在使用 Laravel 5.2 通过 DB Facade 和 select 方法捕获和检索 MySQL 错误代码和消息时遇到了麻烦。

我想要做的是选择/调用一个 MySQL 函数,该函数在带有参数的表中插入一个简单的行。但是,如果不能为空的列的参数为空怎么办? MySQL 抛出错误 (Error Code: 1048)。

问题是在这些情况下,我在 Laravel 中没有收到任何 错误/异常,我不知道插入是否成功或没有以正确的方式处理错误。

这是我的代码:

    DB::beginTransaction();
    try{            
        $statement = "select mySQLFunction('".$param."')";            
        DB::select($statement);                            
        DB::commit();            
    }catch(\Exception $e){            
        DB::rollback();
        Log::error('Exception: '.$e->getMessage());
    }   

我想知道是否有办法捕获这种错误代码和消息,以便 Laravel 应用程序可以知道 MySQL 数据库中存在错误。也可以在成功的情况下获取 MySQL 函数的返回值。

提前致谢!

【问题讨论】:

    标签: php mysql laravel exception-handling laravel-5.2


    【解决方案1】:

    Laravel 使用 PDO,因此您可以使用返回 SQLSTATE 错误和消息的 errorInfo 变量。基本上,你需要使用$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..
        // ....
    }
    

    【讨论】:

    • 如何在控制器中使用,特别是在循环运行多个查询时?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2019-12-31
    • 1970-01-01
    • 2012-11-18
    • 2018-01-11
    • 2022-01-08
    相关资源
    最近更新 更多