I was curious if there is a way we can check if there is a constraint violation error when delete or insert a record into the database.
引发的异常称为"QueryException",但这可能是一系列错误.如果我们能在异常中判断具体错误是什么,那就太好了.
I was curious if there is a way we can check if there is a constraint violation error when delete or insert a record into the database.
引发的异常称为"QueryException",但这可能是一系列错误.如果我们能在异常中判断具体错误是什么,那就太好了.
You are looking for the 23000 Error code (Integrity Constraint Violation)
. If you take a look at QueryException
class, it extends from PDOException
, so you can access to $errorInfo
variable.
To catch this error, you may try:
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 (...)'
To be more specific (Duplicate entry, not null, add/update child row, delete parent row...), it depends on each DBMS:
SQLSTATE
代码的约定,因此可以从数组$e->errorInfo[0]
返回第一个值,或者直接调用$e->getCode()
$e->errorInfo[1]
返回第二个值对于laravel来说,处理错误很容易,只需在"app/start/global.php"文件中添加以下代码(或创建一个service provider):
App::error(function(\Illuminate\Database\QueryException $exception)
{
$error = $exception->errorInfo;
// add your business logic
});