我在 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]
等没有运气。
这有可能吗?
最佳答案
如果返回以下内容:
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"
关于php - 从 PDOException $e 返回特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31692094/