Stichoza / google-translate-php

🔤 Free Google Translate API PHP Package. Translates totally free of charge.
MIT License
1.79k stars 380 forks source link

How to get all exception? #172

Closed taiviemthoi closed 3 years ago

taiviemthoi commented 3 years ago

As in the package documentation, there are some errors like 503, 429, 413, 403

Currently, I am currently getting error 429 when requesting many times, and google block ip. The remaining bugs I don't know the current way to spawn it

In the project I want to catch all possible errors and try again with another service

try {
    $tr = new GoogleTranslate();
    $tr->setSource('en');
    $tr->setTarget('ka');
    $tr->translate('Hello World!');

} catch (\Throwable $throwable) {
    if ($throwable instanceof \ErrorException || $throwable instanceof \UnexpectedValueException) {
        // Error occurred when translating with google api free 
        // Translate with another service
    } else {
        // Stop program and error message due to my code 
    }
}

I don't know if it's reasonable to handle throwing errors when using the free api like that (I'm concerned there are other exceptions when using this package, or other errors when calling api free, but can't catch ) thanks for the extras Thank you

Stichoza commented 3 years ago

There are only ErrorException and UnexpectedValueException thrown by this package. All HTTP errors from Google are thrown as ErrorException. You can check which HTTP error code is by retrieving the exception code $e->getCode(), exception codes are mapped to HTTP status codes.

For example, you can use:

try {

    $tr = new GoogleTranslate();
    $tr->setSource('en');
    $tr->setTarget('ka');
    $tr->translate('Hello World!');

} catch (ErrorException $e) {

    if ($e->getCode() === 429) {
        // We hit the request limit
    } elseif ($e->getCode() === 413) {
        // Translated text is too large
    }

} catch (UnexpectedValueException $e) {
    // Unable to decode response from Google Translate.
} catch (Throwable $e) {
    // Any other error
}
taiviemthoi commented 3 years ago

@Stichoza thank you so much.

What about errors 503, 403, ... then it will go to Throwable right?

Stichoza commented 3 years ago

Those errors are all gathered in ErrorException, including 503 and 403. I just didn't listed it all in the example because someday there might be other codes added too, depends on Google.