简体   繁体   English

如何通过Python套接字处理自定义异常?

[英]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 : 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 : 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!' 打印语句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. 问题是,当您调用conn.send(e)时,您没有在侦听器中引发异常,而只是异常发送为普通数据(就像您可以发送的任何其他对象一样),而conn.recv()只是给您发送的对象无关紧要。 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!'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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