0

I have an api call being made in Laravel using Guzzle/Http. When an error happens I catch it in a try/catch block. I then get the message, but the problem is, I don't want this ugly message that comes back but rather the actual nested message within the $e exception variable. The problem is that the getMessage() method returns a long string from Guzzle.

Error String from $e->getMessage().

"""
Client error: `POST http://mywebApp.com/api/users` resulted in a `422 Unprocessable Entity` response: \n
{"message":"The given data was invalid.","errors":{"email":["This email is not unique"]}}]\n
"""

All I want from this string is:

This email is not unique

The API call

use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;

try {
    $client->request('POST', 'http://mywebApp.com/users', [
      'name' => 'John Doe',
      'email' => 'nonuniqueemail@test.com',
    ]);
} catch (RequestException $e) {
   $test = $e->getMessage();
   dd($test) //The long message from above
}
CodeConnoisseur
  • 1,452
  • 4
  • 21
  • 49
  • Does this answer your question? [Handle Guzzle exception and get HTTP body](https://stackoverflow.com/questions/19748105/handle-guzzle-exception-and-get-http-body) – Don't Panic Mar 28 '22 at 22:38
  • @Don'tPanic turns out I was using the wrong exception type. I needed to use `BadResponseException` instead of `RequestException` which allowed me to actually get the contents of the error with `$e->getResponse()->getBody()->getContents()['errors']` – CodeConnoisseur Mar 29 '22 at 12:45

1 Answers1

2

If you look closely, the response body is actually a json and can be converted into an array containing the message and an array of errors. You can call json_decode($data, true) and you should get an associative array of the response. In your case something like this should work.

$response = $client->request('POST', 'http://mywebApp.com/users', [
    'name' => 'John Doe',
    'email' => 'nonuniqueemail@test.com',
]);
$bodyData = $response->getBody();
$errors = json_decode($bodyData, true)['errors'];
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
Aless55
  • 2,652
  • 2
  • 15
  • 26