Python3 Catch errors when from self.connect(('badhost',6667)) - sockets

Looks like asyncio is the module to use. I'll leave this question up anyway, because it doesn't look like there is a way to catch specific errors with asynchat.
class mysocket(asynchat.async_chat):
terminator = b'\n'
def __init__(self,sock=None):
asynchat.async_chat.__init__(self,sock)
self.create_socket()
# Try always succeeds with self.connect
try:
self.connect(('badhost',6667))
print('command always successful')
except:
print('This never gets printed')
How do I catch errors from the self.connect() method that causes an uncaught exception.
error: uncaptured python exception, closing channel <main.mysocket badhost:6667 at 0x7f0a03e66a58> (:[Errno 111] Connection refused [/usr/lib/python3.4/asyncore.py|read|83] [/usr/lib/python3.4/asyncore.py|handle_read_event|439] [/usr/lib/python3.4/asyncore.py|handle_connect_event|447])
All that is left to try is overwrite the handle_connect_event() method and put asyncore.handle_connect_event(self). I would like to get a professional answer to this dilemma.

Try to override default handle_error method:
def handle_error(self):
t, v, tb = sys.exc_info()
if t == socket.error:
# do smth with it
print("Connect error")

Related

Test that an exception is handled correctly with pytest

I have a block of try-exception code and I want to test if the block works properly? I wonder if there is a way to test this block with a unit test using pylint? This is the snipent I have:
class data_type(Enum):
SESSIONS = 0
RUNS = 1
def find_filter(data_type)
try:
if data_type.name == 'SESSIONS':
return {}
elif data_type.name == 'RUNS':
#Filter out rerun jobs
filter = {
"filter":{
"attName":"is_rerun",
"operand":"IN",
"#c":".InFilter",
"values":["FALSE"]
}
}
return filter
except AttributeError as erro:
loghandler.critical('Error in creating count query: {}'.format(erro))
I want to test if the data_type is not a valid enum member, the exception catches it before the execution goes to if statement. For example if:
find_filter('')
is called I like to see that the except AttributeError as erro captures the error and the error is logged.
Is there a way to do that?
PS: I know with pytest.raises() I can test if a raised error is really raised? But as far as I understand pytest.raises() does not work for testing the exception block of a try-exception case.
Any suggestion please?
Thanks.

Error handling of PipelineModel.load(PATH) if path doesn't exist Pyspark

I want to do an error handling of PipelineModel.load(PATH) i.e want to check if path exists if it doesn't exist, I want to exit the code so was trying try except block but don't exactly know what the error I should be expecting, Below is the snippet for same
try:
pipelineModel = PipelineModel.load(PATH)
except InvalidInputException:
print('Path Does not exist')
sys.exit(0)
Below is the error message
NameError: name 'InvalidInputException' is not defined
try:
pipelineModel = PipelineModel.load(S3LOC)
except Exception as e:
print('Exception Message ',e.args)
print('Model is not deployed')
sys.exit(0)
This snippet worked for me

Can I raise and handle exceptions in the same function

I am raising an exception and trying to handle the exception in snippet. The raising exception part and handling exception part are done in a function. Is it wrong to do so?
import sys
def water_level(lev):
if(lev<10):
raise Exception("Invalid Level!")
print"New level=" # If exception not raised then print new level
lev=lev+10
print lev
try:
if(level<10):
print"Alarming situation has occurred."
except Exception:
sys.stdout.write('\a')
sys.stdout.flush()
else:
os.system('say "Liquid level ok"')
print"Enter the level of tank"
level=input()
water_level(level) #function call
The output is not handling exception. Can someone explain me why?
It is better to just raise the exception in the function and then catch it it when you call the function so your function does not do too much and your error handling is independent. And it makes your code simpler.
Your code never reached your except clause because if the water level is too low it raises an exception and jumps out of the function and if it was okay it just reaches the else clause. The print statement in your try clause is also never reached because it is the same condition than the one that raises your exception and that one jumps out.
Your code should be something like that...
import sys
import os
def water_level(level):
#just raise exception in function here
if level < 10:
raise Exception("Invalid Level!")
level = level + 10
print("New level=") # If exception not raised then print new level
print(level)
#function call
print("Enter the level of tank")
#cast to int
level=int(input())
try:
#call function in here
water_level(level)
#catch risen exceptions
except Exception as e:
sys.stdout.write('\a')
sys.stdout.flush()
#print exception(verification)
print(e)
print("Alarming situation has occurred.")
else:
os.system('say "Liquid level ok"')
Note that i corrected some other flaws
import os was missing
you should cast your input() to a number so you can do number comparisions and additions
try to avoid to catch the least specific Exception Exception because you will catch every other Exception too.(thats why i added the print(e)) -> think about custom exceptions

error 9 Bad file descriptor error using sockets in python

I am trying to implement a very basic code of client server in python using non blocking sockets. I have made two threads for reading and writing.
My client code is below.
import sys
import socket
from time import sleep
from _thread import *
import threading
global s
def writeThread():
while True:
data = str(input('Please input the data you want to send to client 2 ( to end connection type end ) : '))
data = bytes(data, 'utf8')
print('You are trying to send : ', data)
s.sendall(data)
def readThread():
while True:
try:
msg = s.recv(4096)
except socket.timeout as e:
sleep(1)
print('recv timed out, retry later')
continue
except socket.error as e:
# Something else happened, handle error, exit, etc.
print(e)
sys.exit(1)
else:
if len(msg) == 0:
print('orderly shutdown on server end')
sys.exit(0)
else:
# got a message do something :)
print('Message is : ', msg)
if __name__ == '__main__':
global s
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('',6188))
s.settimeout(2)
wThread = threading.Thread(None,writeThread)
rThread = threading.Thread(None,readThread)
wThread.start()
rThread.start()
s.close()
Question:
I know this can be implemented through select module too but I would like to know how to do it this way.
Your main thread creates the socket, then creates thread1 and thread2. Then it closes the socket (and exits because the program ends after that). So that when thread1 and thread2 try to use it, it's no longer open. Hence EBADF (Bad file descriptor error).
Your main thread should not close the socket while the other threads are still running. It could wait for them to end:
[...]
s.settimeout(2)
wThread = threading.Thread(None,writeThread)
rThread = threading.Thread(None,readThread)
wThread.start()
rThread.start()
wThread.join()
rThread.join()
s.close()
However, since the main thread has nothing better to do than wait, it might be better to create only one additional thread (say rThread), then have the main thread take over the task currently being performed by the other. I.e.
[...]
s.settimeout(2)
rThread = threading.Thread(None,readThread)
rThread.start()
writeThread()

How to make Play print all the errors

In our Scala, Play, Reactivemongo we have a big problem with exception handling - when there is an error, in Iteratee/Enumeratee or in Actor system Play just swallows it, without logging any error to the output. So we effectively need to guess where, and why this error might happen.
We made Globals override, to always print the error, and specified logger.root=TRACE, but still saw no output, from which we could analyse our problems.
How to forcebly make Play print all the errors
Didn't found the way to explicitly log everything but there is a way to log exceptions locally.
I did this:
def recover[T] = Enumeratee.recover[T] {
case (e, input) => Logger.error("Error happened on:" + input, e)
}
and then used it on all the enumeratees that can produce errors
def transform(from: Enumerator[From]): Enumerator[String] = {
heading >>> (from &> recover[From] ><> mapper) >>> tailing
}
here, mapper throws exception, and they are all logged.
I think your problem is with how Future works in scala, let's take the following exemple :
val f :Future[Int]= Future {
throw new NullPointerException("NULL")
1
}
f.map(s1 => {println(s" ==> $s1");s" ==> $s1"})
This code will throw an exception but the stack trace will not be printed as futures handle the error.
If you want to get the error that happened you can
just call:
f.onComplete{
case Success(e) => {}
case Failure(e) => e.printStackTrace()
}
e is a throwable that you can use as you want to handle the error.
At the solution I used, is override through ErrorHandling in Play https://www.playframework.com/documentation/2.4.2/ScalaErrorHandling, basically creating ErrorHandler that logs all the errors, with needed detalization.