Handle python exception does not work - python

I am new to Python and facing some issues with exception handling.
When I create a socket and connect it to an IP/port, I want to handle the socket exceptions and not display Python errors on console. I did that with the help of try and except.
try:
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((self.host, self.port))
except error:
print 'Socket Error'
But I still get the error printed on console
error: uncaptured python exception, closing channel <SClient 20.0.0.1:5000 at 0x7fe94e0e2e18> (<class 'socket.error'>:[Errno 111] Connection refused [/usr/lib/python2.7/asyncore.py|read|83] [/usr/lib/python2.7/asyncore.py|handle_read_event|446] [/usr/lib/python2.7/asyncore.py|handle_connect_event|454])
Please advice

try:
a == b
except Exception as e:
print "error: %s"%(e)
Use this format.

Related

How do I check if I connected to the server? Python Sockets

I haven't tested that yet, but if the connection will not be executed, will this last sentence be printed?
def connect_to():
print(f"[*] Connecting to {receiver_ip}:{receiver_port}")
socket.connect((receiver_ip, receiver_port))
print(f"[+] Connected")
How can I check if I connected properly and make a proper if statement?
When a socket fails to connect, it will raise a socket.error exception. You can catch that specific error using some error handling techniques in Python.
import socket
def connect(ip, port):
s = socket.socket()
try:
print(f"Connecting to {ip}:{port}")
s.connect((ip, port))
except socket.error as msg:
print(f"Failed to connect: {msg}")
else:
print(f"Successfully connected to {ip}:{port}")
How can I check if I connected properly and make a proper if statement?
The except block will be executed if the specified error is caught in the try block. On the other hand, the else block will be executed when no errors were raised or handled. You can view the except block as "if error" and the else block as "if not error".
Alternatively, you can catch an error and re-raise it with your custom message.
import socket
def connect(ip, port):
s = socket.socket()
try:
print(f"Connecting to {ip}:{port}")
s.connect((ip, port))
except socket.error as msg:
raise socket.error(f"Failed to connect: {msg}")
print(f"Successfully connected to {ip}:{port}")
By catching and re-raising, you don't have to use the else block anymore.
Use try except to catch the errors and if the connection is successful

Python Except 'socket' object has no attribute 'error'

I'm writing test script for a TCP Server in Python 3.8.
The script worka well, but now I'm tring to implemente a more efficient error catching in order to identify timeout error.
To do that I started to catch the errors and the timeout error for the socket connect.
This is my SocketConnect function:
def SocketConnect( host, port ):
global socketHandle
opResult = errorMessagesToCodes['No Error']
# Set Socket Timeout
socketHandle.settimeout(1)
logging.debug("Connect")
try:
socketHandle.connect((host, port))
except socketHandle.error as e:
opResult = errorMessagesToCodes['Socket Error']
logging.error("!!! Socket Connect FAILED: %s" % e)
return opResult
The socket handler is valid and, in order to test the timeout, I disable the server.
After one second after the connect the code goes to the except but I get this error:
socket.connect((host, port))
socket.timeout: timed out
During handling of the above exception, another exception occurred:
except socket.error as e:
AttributeError: 'socket' object has no attribute 'error'
Is there something missing?
Because I don't understand why socket object ha no attribute error. I think this is a standard error for socket interface.
Thanks in advance for the help.
UPDATE:
I tried to do a basic test (starting from a blank project): only a socket create and a socket connect (with a server not in listening mode) to simulate a timeout.
This is the code:
import socket
import logging
try:
socketHandle = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socketHandle.error as e:
logging.error("Socket Create FAILED: %s" % e)
socketHandle.settimeout(1)
try:
socketHandle.connect(('localhost', 2000))
except socketHandle.error as e:
logging.error("!!! Socket Connect FAILED: %s" % e)
The connect goes into timeout but I still get the error:
except socketHandle.error as e:
AttributeError: 'socket' object has no attribute 'error'
I really don't know what is happening.
UPDATE 2:
I made some other tests, and if I use the try-catch inside the connect function I get the error but if I use the try catch in the main a did not get any error.
Best regards,
Federico
The error is due to you redefining the module name socket; which is what contains socket.error. You are trying to access module level constants (in this case error from the socket module), from a socket object. You could also tighten the error handling to only catch a timeout. This may be needed anyhow, as it appears socket.error does not cover socket.timeout. Changing your socket name should solve the issue:
def SocketConnect(socx, host, port ):
opResult = errorMessagesToCodes['No Error']
# Set Socket Timeout
socx.settimeout(1)
logging.debug("Connect")
try:
socx.connect((host, port))
except socket.timeout as e:
opResult = errorMessagesToCodes['Socket Error']
logging.error("!!! Socket Connect FAILED: %s" % e)
return opResult

Catch "Could not open connection to gateway" in sshtunnel.py

Every now and then setting up a tunnel using sshtunnel.py fails because the gateway (ssh_host) complains the first time I connect to it. I would like to give it a few retries before giving up:
for attempt in range(5):
try:
forwarder.start()
except Exception, e:
print 'Error (trying again in five seconds):\n' + format(e.message))
time.sleep(5)
else:
break
else:
print 'Failed to setup a connection to the gateway'
sys.exit(1)
However, the error is not 'detected'. I took a peek in the sshtunnel.py code and found that the following code catches the related Paramiko exception:
except paramiko.ssh_exception.AuthenticationException:
self.logger.error('Could not open connection to gateway')
return
How do I catch this in my try:?
An SSHTunnel.py project member advised me to add forwarder._check_is_started() to my code:
for attempt in range(5):
try:
forwarder.start()
forwarder._check_is_started()
except BaseSSHTunnelForwarderError as e:
print 'Error (trying again in five seconds):\n' + format(e.message))
time.sleep(5)
else:
break
else:
print 'Failed to setup a connection to the gateway'
sys.exit(1)

Create Socket Errors on Purpose / Python Script

I want to create socket errors (By doing things, obviously) but I've no idea how I should test if my script handles errors properly (If it dectes them.)
Currently, my code is this:
except socket.error as err:
print "Connection lost, waiting..."
time.sleep(5)
In theory, it should handle all the socket errors, print and then sleep (It's a part of a while loop.).
Any idea of how can I test it to see how it handles errors?
Use the raise statement:
try:
raise socket.error
except socket.error as err:
print "Connection lost, waiting..."
time.sleep(5)
Yet another example:
try:
raise AttributeError
except AttributeError:
print 'Sorry'
#Sorry
Also take a look at here and here

Testing socket connection in Python

This question will expand on: Best way to open a socket in Python
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.
Edit:
I tried this:
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
but the alert function is called even when that connection should have worked.
It seems that you catch not the exception you wanna catch out there :)
if the s is a socket.socket() object, then the right way to call .connect would be:
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# originally, it was
# except Exception, e:
# but this syntax is not supported anymore.
except Exception as e:
print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
s.close()
Always try to see what kind of exception is what you're catching in a try-except loop.
You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.
You can use the function connect_ex. It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as errno in C):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((host, port))
s.close()
if result:
print "problem with socket!"
else:
print "everything it's ok!"
You should really post:
The complete source code of your example
The actual result of it, not a summary
Here is my code, which works:
import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
When the server listens, I get nothing (this is normal), when it
doesn't, I get the expected message:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
12 years later for anyone having similar problems.
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
doesn't work because the port '80' is a string. Your port needs to be int.
try:
s.connect((address, 80))
This should work.
Not sure why even the best answer didnt see this.

Categories