Reputation: 1088
I am PUTing to a restful blog API. There is simple error checking in the API. If the entry_name or entry_body is less than 8 characters, he response is as follows:
{
"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."
}
}
In my web page I get this:
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...)
I don't understand how I can catch the exception prior to guzzle spilling out the error like above.
I want to test for failure and if failure i want to display the message(s).
This is the code I have to catch exceptions:
This is my code:
try {
$response = $client->request('PUT', $theUrl);
$theBody = $response->getBody();
} catch (RequestException $e) {
echo $e;
}
but it sails right past the above block :-(
Upvotes: 0
Views: 1201
Reputation: 1042
If you don't want Guzzle 6 to throw exceptions for 4xx and 5xx at all, you need to create a handler stack WITHOUT the http_errors middleware which is added to the stack by default:
$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);
Upvotes: 2