如果答案是404,如何避免引发异常?

问题描述 投票:-1回答:1

我的情况也没有结果。但是Guzzle抛出了一个异常,结果,我的承诺被“拒绝”了。是否可以更改此行为?

enter image description here

如果不可能,我可以获得状态码吗?如果我写类似:

$item['reason']->code

我有一个错误。我认为这个领域是私人的。并且此对象没有getStatusCode方法。

所以我需要200和404结果。 500等对我来说并不重要。

php guzzle
1个回答
0
投票

通常我们只是捕获那些异常,并提供一些逻辑,例如:

$emptyResult = [];
try{
    //your code that should work goes here
    $result = getItemsFromApi();
    return json_encode($result);
} catch(ClientException $e){
  if($e->getCode() == '404'){
     /*warning: in our case body is json already, not sure if your is the same */
     return $e->getResponse()->getBody();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.