Guzzle 6.x并捕获异常/ PHP

时间:2016-11-13 08:54:34

标签: php json rest api guzzle

我正在寻找一个宁静的博客API。 API中有简单的错误检查。如果entry_name或entry_body小于8个字符,则响应如下:

/**
 * @Route("/todo/details/{id}", name="todo_details")
 */
public function detailsAction($id){
   $todo = $this->getDoctrine()
   ->getRepository('AppBundle:Todo')
   ->find($id);

    return $this->render('todo/details.html.twig', array(
        'todo' => $todo
    ));       
}

在我的网页上,我得到了这个:

{
  "status":"failure",
 "message":{
        "entry_name":"The entry_name field must be at least 8 characters in length.",
        "entry_body": The entry_body field must be at least 8 characters in length." 
        }
}

我不明白如何在guzzle之前发现异常,如上所述。

我想测试失败,如果失败,我想显示消息。

这是我必须捕获异常的代码:

这是我的代码:

Type: GuzzleHttp\Exception\ClientException

Message: Client error: `PUT https://www.example.com/api/v1/Blog/blog`   
resulted in a `400 Bad Request` response: {"status":"failure","message":
{"entry_name":"The entry_name field must be at least 8 characters in 
length.","entry_body" (truncated...)

但是它正好经过上面的区块: - (

1 个答案:

答案 0 :(得分:1)

如果您不希望Guzzle 6完全抛出4xx和5xx的异常,则需要创建一个handler stack没有http_errors中间件,默认情况下会添加到堆栈中:

$handlerStack = new \GuzzleHttp\HandlerStack(\GuzzleHttp\choose_handler());

$handlerStack->push(\GuzzleHttp\Middleware::redirect(), 'allow_redirects');
$handlerStack->push(\GuzzleHttp\Middleware::cookies(), 'cookies');
$handlerStack->push(\GuzzleHttp\Middleware::prepareBody(), 'prepare_body');

$config = ['handler' => $handlerStack]);

$client = new \GuzzleHttp\Client($config);