【问题标题】:Catch errors with Laravel API Resource使用 Laravel API 资源捕获错误
【发布时间】:2020-10-04 15:32:32
【问题描述】:

我正在尝试使用 Laravel API 资源并通过发送特定的 HTTP 代码来处理错误消息

这是我的代码:

public function show($id)
{

    try {
        return FruitResource::make(Fruit::find($id));
    }
    catch(Exception $e)
    {
        throw new HttpException(500, 'My custom error message');
    }
}

当我尝试访问路由时,系统会忽略我的 try/catch。

我自愿访问一个不在数据库中的对象。我有ErrorException 和消息Trying to get property 'id' of non-object

我希望能够在此处发送我自己的异常,以防用户尝试访问不存在的数据。并返回一个 json 错误。

【问题讨论】:

  • return response()->json(['error' => 'Custom error message'], 500]);
  • 是的,我知道。但这里的问题是我在 Try/Catch 之前仍然有一个异常
  • 为什么要把这个模型调用放在try里面,catch什么时候也可以在编译时处理,你可以检查给定id是否存在一行

标签: php laravel


【解决方案1】:

试试这个(注意Exception之前的\):

public function show($id)
{

    try {
        return FruitResource::make(Fruit::find($id));
    }
    catch(\Exception $e)
    {
        throw new HttpException(500, 'My custom error message');
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-04
    • 2018-04-05
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2020-06-13
    • 2020-03-23
    • 1970-01-01
    相关资源
    最近更新 更多