Specify an exception class to catch or reraise the exception - how to catch exceptions in proper way?

In Sonar lint I see this message:

Specify an exception class to catch or reraise the exception

My class:

    class GetCountryByIPApiView(APIView):
        def get(self, request, *args, **kwargs):
            ip_address = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get(
                'REMOTE_ADDR', '')).split(',')[-1].strip()
            try:
                ip_country = DbIpCity.get(ip_address, api_key='free').country
            except:
                ip_country = 'US'
            return Response({'country_code': ip_country.lower()}, status=status.HTTP_200_OK)

DbIpCity class:

How should I improve this?

See 8. Errors and Exceptions — Python 3.10.5 documentation

So should I import all exceptions from the external library and use them in this way?

from ip2geotools.errors import IpAddressNotFoundError, PermissionRequiredError, \
                                InvalidRequestError, InvalidResponseError, ServiceError, \
                                LimitExceededError

class GetCountryByIPApiView(APIView):
    def get(self, request, *args, **kwargs):
        ip_address = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get(
            'REMOTE_ADDR', '')).split(',')[-1].strip()
        try:
            ip_country = DbIpCity.get(ip_address, api_key='free').country
        except (AddressNotFoundError, PermissionRequiredError, InvalidRequestError, InvalidResponseError, ServiceError, LimitExceededError):
            ip_country = 'US'
        return Response({'country_code': ip_country.lower()}, status=status.HTTP_200_OK)

Does that method have the possibility of raising all those errors?

Do you want all those different errors to be handled the same way? (Is it possible you may want to handle different errors individually?)

If the answer to those two main questions are “Yes”, then yes, that’s how you would appropriately define that.

1 Like

Thanks.

Do you want all those different errors to be handled the same way?

Yes, I do.

Does that method have the possibility of raising all those errors?

As I use DbIpCity class I just noticed that only these can be raised:

ServiceError, InvalidResponseError, IpAddressNotFoundError, PermissionRequiredError, InvalidRequestError

so I can remove LimitExceededError.