Laravel检查约束违规

时间:2014-10-14 14:24:25

标签: php laravel laravel-4 exception-handling

我很好奇是否有办法在删除或将记录插入数据库时​​检查是否存在约束违规错误。

抛出的异常称为“QueryException”,但这可能是各种各样的错误。如果我们可以检查异常是什么特定错误会很好。

5 个答案:

答案 0 :(得分:28)

您正在寻找23000 Error code (Integrity Constraint Violation)。如果您查看QueryException课程,则会从PDOException延伸,因此您可以访问$errorInfo变量。

要捕获此错误,您可以尝试:

try {
  // ...

} catch (\Illuminate\Database\QueryException $e) {
    var_dump($e->errorInfo);
}

// Example output from MySQL
array (size=3)
   0 => string '23000' (length=5)
   1 => int 1452
   2 => string 'Cannot add or update a child row: a foreign key constraint fails (...)'

更具体(重复条目,非空,添加/更新子行,删除父行......),这取决于每个DBMS:

  • PostgreSQLSQL server遵循SQL标准的SQLSTATE代码约定,因此您可以从数组$e->errorInfo[0]返回第一个值或直接调用$e->getCode()
  • MySQLMariaDBSQLite并未严格遵守规则,因此您需要从数组$e->errorInfo[1]
  • 返回第二个值

对于laravel,处理错误很简单,只需在“app / start / global.php”文件中添加此代码(或创建service provider):

App::error(function(\Illuminate\Database\QueryException $exception)
{
    $error = $exception->errorInfo;
    // add your business logic
});

答案 1 :(得分:2)

您也可以尝试

try {
       ...
    } catch ( \Exception $e) {
         var_dump($e->errorInfo );
    }

然后查找错误代码。

这会捕获包括QueryException

在内的所有异常

答案 2 :(得分:2)

首先把它放在你的控制器中

use Exception;

第二个使用try catch这样的错误来处理错误

try{    //here trying to update email and phone in db which are unique values
        DB::table('users')
            ->where('role_id',1)
            ->update($edit);
        return redirect("admin/update_profile")
               ->with('update','update');
            }catch(Exception $e){
             //if email or phone exist before in db redirect with error messages
                return redirect()->back()->with('phone_email','phone_email_exist before');
            }

此处的新更新无需使用尝试捕获您可以轻松地在验证规则中执行此操作,因为以下代码已自动执行

public function update(Request $request, $id)
{
    $profile = request()->all();
    $rules    = [
            'name'                       => 'required|unique:users,id,'.$id,
            'email'                      => 'required|email|unique:users,id,'.$id,
            'phone'                      => 'required|unique:users,id,'.$id,
    ];
    $validator = Validator::make($profile,$rules);
    if ($validator->fails()){
        return redirect()->back()->withInput($profile)->withErrors($validator);
    }else{
        if(!empty($profile['password'])){
            $save['password'] = bcrypt($profile['password']);
        }
        $save['name']                  = $profile['name'];
        $save['email']                 = $profile['email'];
        $save['phone']                 = $profile['phone'];
        $save['remember_token']        = $profile['_token'];
        $save['updated_at']            = Carbon::now();

        DB::table('users')->where('id',$id)->update($save);
        return redirect()->back()->with('update','update');
    }
}

其中id与您编辑的记录有关。

答案 3 :(得分:0)

您可以在app / start / global.php文件中添加以下代码,以便打印异常

App::error(function(QueryException $exception)
{
  print_r($exception->getMessage()); 
 });

在文档

中查看此part

答案 4 :(得分:0)

如果您正在使用Laravel version 5,并且希望对特定情况进行全局异常处理,则应将代码放入report文件的/app/Exception/Handler.php方法中。这是我们如何在其中的一个微服务中执行此操作的示例:

public function render($request, Exception $e)
{
    $response   = app()->make(\App\Support\Response::class);
    $details = $this->details($e);

    $shouldRenderHttp = $details['statusCode'] >= 500 && config('app.env') !== 'production';
    if($shouldRenderHttp) {
        return parent::render($request, $e);
    }

    return $response->setStatusCode($details['statusCode'])->withMessage($details['message']);
}

protected function details(Exception $e) : array
{
    // We will give Error 500 if we cannot detect the error from the exception
    $statusCode = 500;
    $message = $e->getMessage();

    if (method_exists($e, 'getStatusCode')) { // Not all Exceptions have a http status code
        $statusCode = $e->getStatusCode();
    } 

    if($e instanceof ModelNotFoundException) {
        $statusCode = 404;
    }
    else if($e instanceof QueryException) {
        $statusCode = 406;
        $integrityConstraintViolation = 1451;
        if ($e->errorInfo[1] == $integrityConstraintViolation) {
            $message = "Cannot proceed with query, it is referenced by other records in the database.";
            \Log::info($e->errorInfo[2]);
        }
        else {
            $message = 'Could not execute query: ' . $e->errorInfo[2];
            \Log::error($message);
        }
    }
    elseif ($e instanceof NotFoundHttpException) {
        $message = "Url does not exist.";
    }

    return compact('statusCode', 'message');
}

我们使用的Response类是Symfony\Component\HttpFoundation\Response as HttpResponse的简单包装,它以更适合我们的方式返回HTTP响应。

看看documentation,很简单。

相关问题