Unable to handle exception

Viewed 504

I am using clearbit module to get the company information from the domain name. I tried to handle HTTPException, but somehow it is not recognized and throwing one more Exception NameError.

import clearbit 
def abc(i): 
try: 
  company = clearbit.Company.find(domain=i,stream=True) 
  if company['name'] is None: 
           return "No customer" 
  else: return company['name'] 
except HTTPError as e: 
   s="No customer" 
    return s 
abc('244treqda.com')
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
<ipython-input-152-43005b4345c0> in abc(i)
      3     try:
----> 4         company = clearbit.Company.find(domain=i,stream=True)
      5         if company['name'] is None:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\clearbit\enrichment\company.py in find(cls, **options)
     15 
---> 16         return cls.get(url, **options)
     17 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\clearbit\resource.py in get(cls, url, **values)
     54         else:
---> 55             response.raise_for_status()
     56 

~\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\models.py in raise_for_status(self)
    939         if http_error_msg:
--> 940             raise HTTPError(http_error_msg, response=self)
    941 

HTTPError: 422 Client Error: Unprocessable Entity for url: https://company-stream.clearbit.com/v2/companies/find?domain=244treqda.com

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-153-8c883a3f90d2> in <module>
----> 1 abc('244treqda.com')

<ipython-input-152-43005b4345c0> in abc(i)
      7         else:
      8             return company['name']
----> 9     except HTTPError as e:
     10         s="No customer"
     11         return s

NameError: name 'HTTPError' is not defined

In [119]:



try:
   clearbit.Company.find(domain=i,stream=True)
except urllib2.HTTPError as err:
   if err.code == 422:
       return "No customer"

Expected output "No customer" but getting HTTPError and Attributeerror.

1 Answers

If you look a bit further in the stack trace you see

NameError: name 'HTTPError' is not defined

The HTTPError is not a built in python exception - you'll need to import this from an appropriate module in order to catch that type of exception.

At the top of your python module add from urllib.error import HTTPError and it should work.

Alternatively find the exact HTTPError being thrown from clearbit and import that if the first option doesn't work.

Related