douhuan1648 2016-03-24 23:09
浏览 243

如何使用Laravel 5.2捕获MySQL错误代码和消息?

I'm getting into troubles to capture and retrieve the MySQL Error codes and messages using Laravel 5.2 through the DB Facade with the select method.

What I want to do is to select/call a MySQL function that inserts a simple row in a table with a parameter. However what if the parameter in empty for a column that can't be null? MySQL throws an error (Error Code: 1048).

The problem is that I'm not getting any error/exception in Laravel in those situations and I can't know if the insert succeeded or not to handle the error in the proper way.

Here is my code:

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

I wonder if there is a way to capture this kind of error codes and messages so Laravel application can know there was an error in MySQL database. Also to get the return value of the MySQL function in case of success.

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • duanji1482 2016-03-25 00:05
    关注

    Laravel uses PDO, so you can use the errorInfo variable which returns the SQLSTATE error and the message. Basically, you need to use $e->errorInfo;

    If you want to log all SQL errors into database, you can use the Exception Handler (app/Exceptions/Handler.php and listen for QueryExceptions. Something like this:

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料