Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling Request through SSLError

This is my function for checking link. But it throws an error when the link is fake. For example, it works for twitter.com but not for twitt.com.

class Quality_Check:
    def check_broken_link(self,data):
        url= requests.head(data)

        try:
            if url.status_code==200 or url.status_code==302 or url.status_code==301:
                return True
        except requests.exceptions.SSLError as e:
            return False

qc=Quality_Check()
print(qc.check_broken_link('https://twitte.com'))

When i try to handle the exception by this method it shows following error:

Traceback (most recent call last):
      ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

During handling of the above exception, another exception occurred:

raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='twitte.com', 
port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, 
'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),))

and another one appeared too

requests.exceptions.SSLError: HTTPSConnectionPool(host='twitte.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),))
like image 282
Arpan Ghimire Avatar asked Sep 03 '25 04:09

Arpan Ghimire


1 Answers

Exception happens on the url= requests.head(data) line. So you should include that line in try like so:

class Quality_Check:
    def check_broken_link(self,data):
        try:
            url = requests.head(data)
            if url.status_code == 200 or url.status_code == 302 or url.status_code == 301:
                return True
        except requests.exceptions.SSLError as e:
            return False

qc=Quality_Check()
qc.check_broken_link('https://twitte.com')

Returns False, and on 'https://twitter.com' it returns True, which is the desired result.


And by the way, you can change your line of

if url.status_code == 200 or url.status_code == 302 or url.status_code == 301:

to

if url.status_code in (200, 302, 301):
like image 159
FatihAkici Avatar answered Sep 05 '25 19:09

FatihAkici