调用 role::create 和 permission::create 时捕获异常

Catching exceptions when calling role::create and permission::create

我正在使用 laravel 权限,我经常创建和销毁权限,有时我无法判断用户是否具有特定权限,并且必须检查用户是否具有角色和例如,在我调用 role::create() 之前,许可需要额外的代码。

如果我尝试创建一个已经存在的角色,我会收到一个数据库错误,我希望它正常失败,例如忽略角色创建或权限创建(如果用户具有我要添加的特定权限或角色)。

laravel-permissions 是否带有捕获此类异常的方法,而不是向用户显示数据库错误?

捕获任何 sql 语法或查询错误的最简单方法

Illuminate\Database\QueryException

试试这个

try { 
  role::create()
} catch(\Illuminate\Database\QueryException $ex){ 
  dd($ex->getMessage()); 
  // Note any method of class PDOException can be called on $ex.
} catch(Exception $e){
 // order error handeling
}

[https://laravel.com/api/6.x/Illuminate/Database/QueryException.html]1