Reputation: 1869
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' => '[email protected]',
]);
} catch (RequestException $e) {
$test = $e->getMessage();
dd($test) //The long message from above
}
Upvotes: 0
Views: 712
Reputation: 2709
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' => '[email protected]',
]);
$bodyData = $response->getBody();
$errors = json_decode($bodyData, true)['errors'];
Upvotes: 2