在 laravel 10 站点上,我创建了一个方法,在数据无效的情况下返回 true 或 ItemValidAccess 异常:
/**
* Determine whether logged user have access to complete item
*
* @param \App\Models\Item $item
*
* @return true | ItemValidAccess -
*/
public static function onlyOwnerCanCompleteItem(Item $item): true | ItemValidAccess {
throw_if(
$item->creator_id !== Auth::user()->id,
ItemValidAccess::class,
__('You are not allowed to complete this item')
);
return true;
}
在方法描述中定义 ItemValidAccess 是否正确,因为当我运行 throw_if 时没有 return 语句?
"laravel/framework": "^10.34.2"
提前致谢!
如果您只进行验证,则返回
true
没有任何意义。在这些情况下,只需进行验证,如果失败,则抛出异常并完成,因为如果没有失败,当然您会得到 true
(根本不增加任何值),所以您的代码应该是这样的:
/**
* Determine whether logged user have access to complete item
*
* @throws ItemValidAccess
*/
public static function onlyOwnerCanCompleteItem(Item $item): void {
throw_if(
$item->creator_id !== Auth::user()->id,
ItemValidAccess::class,
__('You are not allowed to complete this item')
);
}
还有一个“问题”,如果抛出异常,名称中包含
Exception
是一个标准:ItemInvalidAccessException
更有意义。