处理laravel livewire函数参数中的异常



如何处理模型类型参数的异常?

public function removeItem(Item $item){
//code...
}
当函数接收到一个不存在的id时,我得到一个404错误屏幕,我宁愿启动一个简单的警报,不破坏表单。

操作参数还能够使用类型提示通过键直接解析模型。

这意味着通过类型提示您的$item作为Itemlivewire试图通过给定的id找到Item。但如果该id不存在,则会抛出一个匹配异常。因此,不需要输入removeItem方法。

要处理函数内部的异常,您只需去掉类型提示并自己获取模型:

use IlluminateDatabaseEloquentModelNotFoundException;
public function removeItem(int $item)
{
try {
Item::findOrFail($item);
// your code...
} catch (ModelNotFoundException $modelNotFoundException) {
// launch your simple alert
} catch (Throwable $th) {
// remaining error handling
}
}

最新更新