【问题标题】:How get InvalidArgumentException with Guzzle?如何使用 Guzzle 获取 InvalidArgumentException?
【发布时间】:2017-11-01 14:14:17
【问题描述】:

我正在通过 Guzzle 发送帖子,并且某些产品返回 InvalidArgumentException 错误,我如何获取此数据?不幸的是,文档中对此一无所知。

这是错误

InvalidArgumentException in functions.php line 324:
json_encode error: Malformed UTF-8 characters, possibly incorrectly encoded

我的收获:

catch (ClientException $e) {

              if ($e->hasResponse()) {
                  $resposta = Psr7\str($e->getResponse());
                  $incrementer->cron_value = $incrementer->cron_value + 1;
                  $incrementer->save();
                  return view('home');
              }
          }
          catch (RequestException $e) {
              return view('home');
              if ($e->hasResponse()) {
                  $incrementer->cron_value = $incrementer->cron_value + 1;
                  $incrementer->save();
                  return view('home');
              }
          }

【问题讨论】:

  • 始终在 try ..catch 块中发送您的请求,例如 try { // Your guzzle action} catch (Exception $e) {echo $e->getMessage(); }
  • 是的,我使用了 try catch,但在 Guzzle 文档中我没有看到任何方法可以得到这种错误。比如我使用了ClientException和RequestException,但是由于错误是InvalidArgumentException,所以没有通过try catch过滤
  • 如果操作正确,所有异常都可以被捕获。向我们展示您的try/catch
  • 好的,我编辑了。 @ceejayoz
  • 只需添加另一个catch...例如catch(InvalidArgumentException $e)。 1 个try 可以有多个catch() 块。或者,您可以通过执行 (catch \Exception $e) 捕获任何异常,然后将 $e 传递给另一个可以 switch 处理异常类型的类,就像 Larvael(在这种情况下是 Symfony)所做的那样。

标签: json laravel rest guzzle


【解决方案1】:

正如您在 Guzzle 的代码中看到的那样,这一行有一个一般异常(来自根命名空间)。

if (JSON_ERROR_NONE !== json_last_error()) {
    throw new \InvalidArgumentException(
        'json_encode error: ' . json_last_error_msg());
}

因此,除了其他异常之外,您还必须捕获它。

try {
    //...
} catch (ClientException $e) {
    // ...
} catch (RequestException $e) {
    // ...
} catch (\InvalidArgumentException $e) {
    // Your UTF error.
}

【讨论】:

  • 完美!谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
相关资源
最近更新 更多