Skip to main content
 首页 » 编程设计

python之如何处理代理类中的不可用主机(ConnectionRefusedError)

2024年10月25日9fff_TT

我有一个非常基本的代理类(一个帮我编码的 friend 坚称它是一个装饰器类)python-mpd2 .

类看起来是这样的

import mpd 
 
class MPDProxy: 
    def __init__(self, host="localhost", port=6600, timeout=10): 
        self.client = mpd.MPDClient() 
        self.host = host 
        self.port = port 
 
        self.client.timeout = timeout 
        self.connect(host, port) 
 
    def __getattr__(self, name): 
        return self._call_with_reconnect(getattr(self.client, name)) 
 
    def connect(self, host, port): 
        self.client.connect(host, port) 
 
    def _call_with_reconnect(self, func): 
        def wrapper(*args, **kwargs): 
            try: 
                return func(*args, **kwargs) 
            except mpd.ConnectionError: 
                self.connect(self.host, self.port) 
                return func(*args, **kwargs) 
        return wrapper 
 
mpd_proxy = MPDProxy() 

到目前为止,只要有可连接的 mpd 主机,它就可以正常工作。如果没有 mpd 服务器,我得到

ConnectionRefusedError: [Errno 111] Connection refused

我正在寻找好的模式来处理这个异常

  • 你能想出一种优雅的方法来防止程序在没有可用主机时崩溃吗?
  • 无论何时调用代理,我应该在代理内部还是外部捕获异常?
  • 将字符串“Host not available”(或类似的)作为返回值是个好主意,还是可以以更好的方式通知调用代理的方法/函数?

请您参考如下方法:

Can you think of an elegant way to prevent the program to crash, when there is no host available?

尝试...除了 ;)


Should I catch the exception within the proxy or outside, whenever the proxy is called?

您应该问自己的问题是“谁*能够*处理该异常?”


显然,代理无法对“修复”ConnectionRefusedError 进行任何明智的处理。所以它必须在上层处理。


Is a string "Host not available" (or similar) as a return value a good idea or can a method/function calling the proxy be informed in a better way?

坏主意。通知“上层”异常发生的正常方法是引发异常。或者让引发的异常向上传播。


具体来说:

class MPDProxy: 
    def _call_with_reconnect(self, func): 
        def wrapper(*args, **kwargs): 
            try: 
                return func(*args, **kwargs) 
            except mpd.ConnectionError: 
                self.connect(self.host, self.port) 
                # ^^^^^^ This lime might raise `ConnectionRefusedError` 
                # as there is no `except` block around, this exception 
                # is automatically propagated      
 
                return func(*args, **kwargs) 
        return wrapper 
 
try: 
    mpd_proxy = MPDProxy() 
    r = mdp_proxy._call_with_reconnect(whatever) 
except ConnectionRefusedError: 
    do_somesible_sensible()