【问题标题】:Php throw is not working from inside catch blockphp throw 在 catch 块内不起作用
【发布时间】:2018-08-09 23:54:22
【问题描述】:

当我调用 $this->get() 并且它在 get 方法内抛出一个不是 ClientException 的异常时,最后一个 catch 块被调用,但是整个方法返回一个 NULL。

我已在最后一个 catch 块中使用 var_dump($e) 确认该错误正在被该 catch 块捕获...但 throw 似乎不起作用!

这让我大吃一惊,我不明白为什么。

public function get(string $url, $params = null): array
{
    $client = new Client();
    try {
        $response = $client->get($url, ['query' => $params]);
        return json_decode($response->getBody(), true);
    } catch (ClientException $e) {
        if (!empty($response = self::handleGuzzleErrors($e, $url))) {
            return $response;
        }
        throw $e;
    } catch (\Exception | \Throwable $e) {
        var_dump($e);
        throw $e;
    }
}
public function getSub(string $url, array $subs, $params = null): array
{
    $url = strtr($url, $subs);
    $result = $this->get($url, $params);
    return $result;
}

【问题讨论】:

    标签: php exception try-catch


    【解决方案1】:

    throw != return

    尝试将您对 $this->get() 的调用包装在 try/catch 中,如下所示:

    public function getSub(string $url, array $subs, $params = null): array
    {
        $url = strtr($url, $subs);
        try {
            $result = $this->get($url, $params);
        } catch (\Exception | \Throwable $e) {
            echo "This gets called";
        }
        return $result;
    }
    

    如果连接失败并抛出错误,则返回 null 之外的任何内容都没有任何意义。

    如果您希望在抛出错误时获得“默认”返回值,请使用 return 而不是 throw

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2012-09-04
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多