Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why PHP is not respecting try catch?

This might be a noob question, but i’m having problems understanding this:

I’m doing a simple function in Laravel, to get a location from an IP address, and the relevant part is this:

try {
    ...
    $ip = $request->ip();
    try {
        $country = $this->getCountry($ip);
        $country_name = $country["country"];
        $country_code = $country["code"];
    } catch (Exception $e) {
        $country_name = null;
        $country_code = null;
    }
    ...
} catch (\Exception $e) {
    return response()->json(['status' => 'error', 'errors' => [$e->getMessage()]], 400);
}

Here i try to get the data of the country using the getCountry trait, which is like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private function getCountry($ip=''): ?array
{
    try {
        $ip     = $ip ? $ip : $defaultip;
        $dir    = DIRECTORY_SEPARATOR;
        $reader = new Reader($path);
        $record = $reader->country($ip);
        return ["country" => $record->country->name, "code" => $record->country->isoCode];
    } catch (Exception $exception) {
        return "cn";
    }
}

Nothing special, just use GeoIP to get the data of the country. Now, as you can see i setted a Try Catch so, if getCountry failed, it would just set the data with null. I tested it sending a private IP address, which should cause an error that would return the data in null, but instead it sended an error message, apparently from the top try catch(The one that returns the json response), while ignoring the try catch inside the getCountry, and the one that should set the data on null, skipping everything after that point. Am i missing something about how the try catch works, or maybe i’m making a mistake somewhere for this to work?

>Solution :

In getCountry, you are catching Exception (without the \ for the namespace which is the one that ships with PHP (docs), but in your calling function your are catching \Exception.
Change it to catch the same \Exception in both statements and it should work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading