【问题标题】:Return specific items from PDOException $e从 PDOException $e 返回特定项目
【发布时间】:2015-10-19 22:34:47
【问题描述】:

我的 routes.php 中有一个 try catch,它运行良好。

Route::get('{provider}/login', function ($provider) {
try
{
OAuth::login($provider, function ($user, $userDetails) 
{
    $user->email = $userDetails->email;
    $user->name = $userDetails->firstName . ' ' . $userDetails->lastName;
    $user->first_name = $userDetails->firstName;
    $user->last_name = $userDetails->lastName;
    $user->picture = $userDetails->imageUrl;
        $user->about = $userDetails->summary;
    $user->save();
    });

    return view('home');

} 
catch (ApplicationRejectedException $e) 
{
    // User rejected application
} 
catch (InvalidAuthorizationCodeException $e) 
{
    // Authorization was attempted with invalid
    // code,likely forgery attempt
}
catch(PDOException $err)
{
    return redirect()->guest('home');
}   
});

我想做的是从 PDOException $err 消息中提取特定项目。

如果我尝试登录但我知道会因 PDO 异常而失败,并且我“dd”了我得到的错误:

QueryException {#397 
#sql: "insert into `users` (`email`, `name`, `first_name`, `last_name`, `picture`, `about`, `facebook_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)"
#bindings: array:9 [?
0 => "mhluzi@email.com"
etc....

我如何获取电子邮件地址?

我已经尝试过各种变体

$err->binding[0] 

等没有运气。

这有可能吗?

【问题讨论】:

  • 为什么不能直接使用$user->email
  • 因为$user在那个阶段没有定义,因为在创建之前就发生了错误:"ErrorException in routes.php line 232: Undefined variable: user"

标签: php mysql pdo laravel-5


【解决方案1】:

如果返回如下:

catch(PDOException $err)
{
    $thisMessage=$err->getMessage();
    dd($thisMessage);
}

整个字符串都可用:

"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'mhluzi@email.com' for key 'users_email_unique' (SQL: insert into `users` 

等等

所以我所做的就是将“'”替换为“*”

然后能够访问我需要的内容。

catch(PDOException $err)
{
    $thisMessage = str_replace("'", "*", $err->getMessage());
    if(preg_match_all('/\*(.*?)\*/',$thisMessage,$thisMatch)) 
    {
        dd($thisMatch[1][0]); //first occurrence which is what we want
    }
}

输出:

"mhluzi@email.com"

【讨论】:

    猜你喜欢
    • 2022-06-17
    • 2023-03-12
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    相关资源
    最近更新 更多