我想使用 Eloquent 创建这样的数据库条目:
MFUser::create(array(
'user_reference' => $this->userReference,
'first_name' => $this->firstName,
'last_name' => $this->lastName,
'user_type_id' => $this->userTypeId,
'email' => $this->email,
'password' => $this->password
));
它运作良好,除了将完全相同的数据放入字段的情况,这是预期的,因为不应该有重复。然后我得到了 QueryExecption。
但是我如何在这里正确地执行错误处理以检查是否发生此查询异常,然后我可以通过 json 从我的服务器向客户端返回响应?
最佳答案
只需将该代码包装在 try
-catch
block 中。像这样:
try {
MFUser::create(array(
'user_reference' => $this->userReference,
'first_name' => $this->firstName,
'last_name' => $this->lastName,
'user_type_id' => $this->userTypeId,
'email' => $this->email,
'password' => $this->password
));
} catch (\Illuminate\Database\QueryException $exception) {
// You can check get the details of the error using `errorInfo`:
$errorInfo = $exception->errorInfo;
// Return the response to the client..
}
关于php - Laravel 模型创建时的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36241924/