Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch socket timeout exception

I would like to catch the socket timeout (preferably in an exception) ... except urllib.error.URLError: can catch it but I need to distinguished between a dead link and a timeout .... If I take out the except urllib.error.URLError: the socket timeout does not catch and script terminates with an socket.timeout error

import urllib.request,urllib.parse,urllib.error
import socket
import http
socket.setdefaulttimeout(0.1)


try:
    file2 = urllib.request.Request('http://uk.geforce.com/html://')
    file2.add_header("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13")
    file3 = urllib.request.urlopen(file2).read().decode("utf8", 'ignore')
except urllib.error.URLError: print('fail')
except socket.error: print('fail')
except socket.timeout: print('fail')
except UnicodeEncodeError: print('fail')
except http.client.BadStatusLine: print('fail')
except http.client.IncompleteRead: print('fail')
except urllib.error.HTTPError: print('fail')

print('done')
like image 504
Rhys Avatar asked Aug 23 '11 20:08

Rhys


People also ask

How do I fix socket timeout exception?

Using try/catch/finally If you are a developer, so you can surround the socket connection part of your code in a try/catch/finally and handle the error in the catch. You might try connecting a second time, or try connecting to another possible socket, or simply exit the program cleanly.

What causes a socket timeout exception?

Socket timeouts can occur when attempting to connect to a remote server, or during communication, especially long-lived ones. They can be caused by any connectivity problem on the network, such as: A network partition preventing the two machines from communicating. The remote machine crashing.

How do I fix Java net SocketTimeoutException read timed out?

A possible solution for this problem within the Tomcat web application is to modify the CONTEXT. XML file, and modify the CONNECTOR definition that governs the workstation browser connectivity to the Tomcat server. Specifically, modify the connectionTimeout value. Increase this value to suppress the error condition.


1 Answers

...
except urllib.error.URLError, e:
    print type(e.reason)

You will see <class 'socket.timeout'> whenever there is a socket timeout. Is this what you want?

For example:

try:
  data = urllib2.urlopen("http://www.abcnonexistingurlxyz.com")
except Exception,e:
  print type(e.reason)
... 
<class 'socket.timeout'>
like image 60
Ruggiero Spearman Avatar answered Oct 19 '22 05:10

Ruggiero Spearman