[英]Guzzle 6.x and catching exceptions / PHP
我正在输入一个宁静的博客API。 API中提供了简单的错误检查功能。 如果entry_name或entry_body少于8个字符,则其响应如下:
{
"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."
}
}
在我的网页上,我得到以下信息:
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...)
我不明白如何在像上面那样抛出错误之前抓到异常。
我想测试失败,如果失败,我想显示消息。
这是我必须捕获异常的代码:
这是我的代码:
try {
$response = $client->request('PUT', $theUrl);
$theBody = $response->getBody();
} catch (RequestException $e) {
echo $e;
}
但它驶过上述街区:-(
如果您根本不希望Guzzle 6抛出4xx和5xx的异常,则需要创建一个没有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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.