Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle exceptions from API #52

Closed
tousignantf opened this issue Feb 22, 2017 · 3 comments
Closed

Handle exceptions from API #52

tousignantf opened this issue Feb 22, 2017 · 3 comments
Labels

Comments

@tousignantf
Copy link

Hello,

I have a problem handling 400 response from API.

My problem is that I need to show a particular message when an admin tries to create a new user with an already used email.

The API returns this when it happens:

Response status code: 400
Response body: - Toggle response

{
    "@context": "\/contexts\/ConstraintViolationList",
    "@type": "ConstraintViolationList",
    "hydra:title": "An error occurred",
    "hydra:description": "email: This value is already used.",
    "violations": [
        {
            "propertyPath": "email",
            "message": "This value is already used."
        }
    ]
}

In my controller however, if I Try/Catch the call to the repository, I only have access to the ClientException (thrown in Mapado\RestClientSdk\RestClient::post), so I can't distinguish the particular "dupplicate email" error from other ones, even if the API sent the information in it's 400 response.

Please help, Merci beaucoup

@jdeniau
Copy link
Member

jdeniau commented Feb 23, 2017

The only solution I think of is to access the response in your catch:

try {
    // do something that will fail
} catch (Mapado\RestClientSdk\Exception\RestClientException $e) {
    $response = $e->getResponse(); // $response should be a Psr\Http\Message\ResponseInterface
    $body = $response->getBody();
    $content = json_decode($body, true);
    var_dump($content['hydra:description']); // should dump ""email: This value is already used."
}

Does this suits your needs ?

@tousignantf
Copy link
Author

Allright, that works!

Thanks a lot! Merci :-)

@jdeniau jdeniau closed this as completed Feb 24, 2017
@jdeniau
Copy link
Member

jdeniau commented Feb 24, 2017

For your information, I updated the README thanks to you: https://github.com/mapado/rest-client-sdk/blob/master/README.md#handling-exceptions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants