Why PHP is not respecting try catch?

Published

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

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?

Source: Laravel

Published
Categorised as laravel, php Tagged ,

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq