DeepLcom / deepl-php

Official PHP library for the DeepL language translation API.
MIT License
202 stars 23 forks source link

Handle json parsing errors #18

Closed VincentLanglet closed 1 year ago

VincentLanglet commented 1 year ago

Hi @daniel-jones-deepl,

We got some errors with this library when using translateText method

$response = $this->client->sendRequestWithBackoff(
            'POST',
            '/v2/translate',
            [HttpClient::OPTION_PARAMS => $params]
        );
        $this->checkStatusCode($response);

        list(, $content) = $response;
        $decoded = json_decode($content, true);

The content thrown by the API is not always a correct json, so json_decode fails and $decoded might be null ; then it creates multiple warning/errors later.

I saw a lot of "unsafe" json_decode are made in this library. So I changed the behavior to this one:

This way we have invalid calls (throwing 400, 500, ...) and invalid responses (invalid json) are treated the same way with a DeeplException instead of some warning/null values/critical php errors.

Thanks for taking a look :)

VincentLanglet commented 1 year ago

Friendly ping @daniel-jones-deepl, @JanEbbing. Does someone have time to take a look ? :)

JanEbbing commented 1 year ago

Just FYI, I'm adding our normal copyright header to the InvalidContentException.php file you created in this PR. I didn't catch this yesterday as we don't yet have CI on Github

VincentLanglet commented 1 year ago

Just FYI, I'm adding our normal copyright header to the InvalidContentException.php file you created in this PR. I didn't catch this yesterday as we don't yet have CI on Github

Of course, no problem !