php - Laravel 模型创建时的错误处理

标签 php laravel

我想使用 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/

相关文章:

laravel - 向特定用户发送推送通知 - Laravel

javascript - 在 WordPress 存档循环中添加 Owl Carousel 而不是帖子缩略图

php - Laravel 多对多关系获取数据

php - 如何更改 WordPress 中的 ABSPATH?

php - 收听 Laravel 5.3 包中的事件

laravel - Laravel setUpBeforeClass上的PHPUnit找不到工厂类

php - 使用 php 和 javascript 生成动态 css

php - 将网站从 .html 更改为 .php,这会影响我的 seo 排名吗

javascript - Laravel 无法使用模态和 ajax 的增量方法添加数量

php - Laravel 4.2 查询错误 - 当其他无缓冲查询处于事件状态时无法执行查询