简体   繁体   中英

How to handle custom exceptions via Python Sockets?

I am using a listener/client pattern to transmit data via sockets between two processes. Unfortunately, I don't know how I can catch exceptions in the client code, which occurred in the listener code. I thought that maybe I can achieve this by simply transmitting the exception via the socket, but that does not work.

Here's my code:

listener.py :

#!/usr/bin/env python

from multiprocessing.connection import Listener

import random


class MyException(Exception):
    pass


def main():
    address = ('localhost', 6000)  # family is deduced to be 'AF_INET'
    listener = Listener(address, authkey='secret password')
    rand = random.randint(1, 101)
    while True:
        conn = listener.accept()
        print 'connection accepted from', listener.last_accepted
        msg = conn.recv()
        # do something with msg
        if msg == 'hello':
            try:
                raise MyException('Oooops')
            except MyException as e:
                print 'Sending {}'.format(e.message)
                conn.send(e)
                # conn.send('Hello world! {}'.format(rand))
        elif msg == 'close':
            conn.close()
            break
    listener.close()

if __name__ == '__main__':
    main()

client.py :

#!/usr/bin/env python

from multiprocessing.connection import Client

from listener import MyException

def main():
    address = ('localhost', 6000)
    conn = Client(address, authkey='secret password')
    conn.send('hello')
    try:
        res = conn.recv()
        print res
    except MyException as e:
        print 'Received error!'
    conn.send('close')
    conn.close()

if __name__ == '__main__':
    main()

The print statement print 'Received error!' in the client will never be executed.

What would be the correct approach to handle errors?

the problem is that you are not raising an exception in the listener when you call conn.send(e) you are just sending an exception as normal data (like any other object you can send) and conn.recv() just gives you the object that was sent, the fact that it is an exception doesn't matter. the easiest way to handle the exception would be to check if it is an instance of an exception (or an instance of a derived exception):

res = conn.recv()
if(isinstace(res,Exception))
    print 'Received error!'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM