【问题标题】:Using the Laravel Eloquent Resource to errors使用 Laravel Eloquent 资源解决错误
【发布时间】:2018-04-05 11:08:57
【问题描述】:

我正在使用 Laravel 5.5,并在我的应用程序中测试新的eloquent resource,我能够以 json 格式返回我的数据,但是,如果我没有数据或发生错误,我该如何返回此资源出错?

返回我的数据的示例:

public function show ($id)
{
   return new ProductResource(Product::find($id));
}

【问题讨论】:

    标签: php laravel api laravel-eloquent


    【解决方案1】:

    添加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
        ]);
    }
    

    【讨论】:

    • 这个isValidResource()是自定义方法吗?
    • 是的,您可以在其中验证资源检查的属性或您想要的任何内容
    • 我应该扩展一些类来使用异常吗?
    • 你只需要扩展Exception。 Laravel 检测是否抛出了 render 方法的异常
    • 对我不起作用。遵循你所说的一切。他只是抛出了很多关于我创建的异常类的错误。
    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2020-10-04
    • 2019-05-29
    相关资源
    最近更新 更多