[英]Using the Laravel Eloquent Resource to errors
我正在使用Laravel 5.5,並在我的應用程序中測試了新的雄辯的資源 ,我能夠以json返回我的數據,但是,如果我沒有數據或發生了什么錯誤,如何從該資源返回錯誤?
示例返回我的數據:
public function show ($id)
{
return new ProductResource(Product::find($id));
}
添加一個if
檢查完整性,如果無效則拋出一個自定義異常
public function show($id)
{
$product = Product::find($id);
if (! $product->isValidResource()) {
throw new InvalidResourceException($product);
}
return new ProductResource($product);
}
然后,您可以在App\\Exceptions
創建異常文件,並在其上聲明方法render
,可以自定義錯誤以顯示
public function render()
{
return response()->json([
'result' => false,
'message' => 'Invalid Resource: '.get_class($this->product) .' identified by '.$this->product->id
]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.