Laravel 5: Guzzle -> getStatusCode on Exception? - php

I am programming a little application for myself. This application is calling to different websites with the package Guzzle.
However, I want to store every request in my database with the time and the request duration time and the request status code I get. The problem I am facing here right now is that I don't know how to get the http status code when the request fails..
This is my code so far:
$client = $this->getGuzzleClient();
$request = $client->post($url, $headers, $value);
try {
$response = $request->send();
return $response->getBody();
}catch (\GuzzleHttp\Exception\RequestException $e){
dd(array($e, $e->getResponse()));
}
The $e->getResponse() returns null. I also tried to use $e->getStatusCode() or $e->getRequest()->getStatusCode(). Both are not working...
To be absolutely sure the request is valid and I deal with a real exception I call to this website https://httpstat.us/503. This returns a 503 http status code...
So, how can I get the http status code? Do you guys have any idea?
Kind regards and Thank You!

If you catch a ServerException you are catching a 5xx, if the code execution enters there Guzzle has received a 5xx. If you catch a RequestException that includes network errors too. If the code execution enters on the RequestException but does not on the ServerException means that for Guzzle is not a 5xx error but a network error.

$errorstatuscode=$exception->status;
// to get error code from Excetion Object

Related

If we throw an exception that's not caught again, do we get an empty response status?

Basically, I was sending a AJAX request with an object with some missing JSON data, and I was wondering why I didn't get a status code and got no response data. The JSON is valid, but there are missing data that won't allow the code to successfully run.
So I tried it several times and the request never returned any data and there was no status code as if the server didn't respond and the request timed out. I tried with a correct JSON and it worked flawlessly (I got a 200 status and a proper server response)
public function getAssets($asset_id) {
try {
$response = $this->_services[$current_service]->get_random_asset($asset_id);
} catch (Exception $e) {
throw new Exception('Something is wrong: '.$e->getMessage(), 500);
}
}
I am not sure if this is correct, but I am guessing if I don't catch the thrown Exception by putting the function call of getAssets() in a try block or any function higher in the stack the server will not send any response and the request will timeout?

CakePHP 3 Http Client timeout error handling

I'm trying to use the CakePHP 3 Http Client to check urls for their response status code (404, 301, 200 etc)
$http = new Client();
$response = $http->get($links[$i]['url'],[],['timeout' => '10']);
$links[$i]['http_status'] = $response->statusCode();
However, if I come across a url that timesout, the entire script fails. I'm having trouble figuring out how to add error handling so that if it does timeout, I can log it and move on.
Any ideas?
The solution was to use try/catch. I had tried this initially but missed the \ before Exception on the catch
try {
// code
} catch (\Exception $e) {
// error
}

SoapClient call returns 500 Internal Server Error

I am trying to connect to an API using PHP and its built-in SoapClient. I have checked against the url I was given through the ill-formatted documents the client gave and $client->__getFunctions() returns a list of three functions. HelloWorld($name), which responds with Hello ~name~, shows me that I am communicating with the server through the SoapClient call and the URL is correct.
However, when I try to access one of the other methods that __getFunctions() gives me, even after copy/pasting the XML from the docs and putting in my own credentials, I am still being given an Internal Server Error faultstring and 500 as faultcode from the SoapFault object.
I am sure that it is my own XML string that is causing the issue but I cannot for the life of me figure out how. Reaching out to the API provider directly hasn't proven helpful. This is my first time dealing with Soap/Web Services so I am unsure of where to go from here.
I did wget http//xxx.xxx.xxx?wsdl and it returned me what looks like a valid XML response, the same one I get when I go directly to the url in the browser. What should I be looking into in order to solve this issue? All of the past API's I've dealt with have been JSON/RESTful so I feel out of my element trying to debug PHP errors.
Edit
I have slowly deleted parts of my method call and parts of my XML string, trying to trigger a different error or something in order to find what I need to fix. What I have found is that by not passing in my XML string, I get a valid response from the $client->FunctionCall(...). It's an "this isn't right" message but it's a message! In fact, passing that function ANYTHING for the xml parameter causes the 500 http faultcode/faultstring. Does this mean that my XMl is poorly formatted or does it mean that there is an issue on their end handling requests?
Second Edit
If I make my $client decleration as follows, I get the faultstring Could not connect to host
$opts = array(
'ssl' => array('ciphers'=>'RC4-SHA')
);
$client = new SoapClient($CREDS['orderingWSDL'], array (
"encoding"=>"ISO-8859-1",
'stream_context' => stream_context_create($opts),
'exceptions'=>true,
));
I am getting more confused the longer I try to fix this.
Sometimes a 500 status coming from a SOAP service could be a SoapFault exception being thrown. To help your troubleshooting, you'll want to be able to inspect both your request XML, and the response XML.
Put your code in try/catch blocks, and use $client->__getLastRequest() and $client->__getLastResponse() to inspect the actual XML.
Example:
$client = new SoapClient('http//xxx.xxx.xxx?wsdl', array('soap_version'=>SOAP_1_1,'trace' => 1,'exceptions' => true));
try {
$response = $client->someFunction();
var_dump($response);
} catch (Exception $e) {
var_dump($e->getMessage());
var_dump($client->__getLastRequest());
var_dump($client->__getLastResponse());
}

Retrieving original body from an http error in Guzzle

I'm making a Guzzle request to an api, and
$request = $this->client->request('GET', 'https://etc', ['http_errors' => false]);
I've had to turn http_errors off as if the API wants to tell me something it does it as a JSON response but it also has a header code of 402.
I can get the response headers back from Guzzle, but I'm unable to get the actual body $request->getBody() as this is just an empty stream on the response object.
Does anyone know how I retrieve the original page despite it providing a 402 http error.
NB: If I don't turn off http_errors, it will throw an exception but the message is wrapped (and truncated).
Any suggestions would be gratefully received.
I stumbled across the answer I was looking for.
If I don't turn off http_errors and catch the exception I can run
$e->getResponse()->getBody()->getContents();
to retrieve the contents of the request.

Guzzle throws 401 or 406 exception

cURL works fine:
curl -H "X-ApiToken: myapitoken" https://api.fulcrumapp.com/api/v2/records
Guzzle does not:
$client = new Client();
$request = $client->createRequest('GET', "https://api.fulcrumapp.com/api/v2/records");
$request->setHeader("X-ApiToken:" , "myapitoken");
$response = $client->send($request);
This responds with a 401 error: not authorized. This is my first time using Guzzle but in my searches I haven't seen this error. Seems like a simple request so I'm not sure why it is failing.
Thank you!
I had to add another header to explicitly tell it to handle json
$request->setHeader("Accept" , "application/json");
Thank you for pointing out that the 401 was a false error - the real error was the 406, which made me read how to actually fix that.
The setHeader method takes the header name without the colon. Change "X-ApiToken:" to "X-ApiToken".

Categories