public function myLogin() {
    try {
      $client = \Drupal::httpClient();
      $request = $client->post('https://targetApi.com/auth/login?fx=1', [
             'json' => [
                 'login' => 'demo',
                 'password' => 'demo1234567',
                 'locale' => 'en'
      $response = json_decode($request->getBody());
      return $respone;
    } catch (\Exception $e) {

When I set wrong password I can catch this in $e->getMessage(). The message is:

Client error: `POST https://targetApi.com/auth/login?fx=1` resulted in a `404 Not Found` response:

So I can catch error, this is fine. But I'd like to get JSON data from It. And if in the try part I have it in $request->getBody(), how can I get it from $e ?

  • What type is $e? If it's a Guzzle exception of some sort you can probably use $e->hasResponse() to see if there's a response, then $e->getResponse() to get it – Clive Mar 26 '19 at 16:14
  • I'm getting Type: GuzzleHttp\Exception\ClientException with get_class($s) – Andy Core Mar 26 '19 at 16:19
  • I'm getting $e->getResponse(), but there is no "auth.user.notfound" in it. How can I get this response? – Andy Core Mar 26 '19 at 17:00
  • 1
    It’s a response object so without checking I’d assume via its getBody() method. Although I think there might be a json method as well. – Clive Mar 26 '19 at 17:17
  • I finally figured it all out. $e->getResponse()->getBody()->getContents() is what I need. – Andy Core Mar 26 '19 at 17:54

This should work

if ($e->hasResponse()) {
    $response = $e->getResponse()->getBody()->getContents();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.