python custom exception handler for a class -


I want to build my application with a redis cache. But maybe not available in our case at all times, I hope that it works well, we use it if it can not work, just logging and ignoring it at this time. For example:

 try: conn.sadd ('s', * array) except: ... 

Because there are many places I conn som some. (Rediscommand) will run, I do not want to try / except everywhere.

Then the solution can be:

 class softcache (redis.StrictRedis): def (key, * p) simpler: try: super (redis.StrictRedis, self) .sadd Leaving (Key, P): .. 

But since many orders are recovered, I have to press them one by one.

Is it possible to customize an exception handler for this class, which can handle all the exceptions coming from this class?

Shut up every default, all the exceptions are probably the worst thing you can do.

However, for your problem, you can write a general cover that only redirects to the connection object.

ReddisWrapper (object): cone = conn # here your reddis __ __getattr def object (self, attr): def wrapper (* args, ** kwargs): # get real reddis Work Fn = getattr (self.conn, attr) # Try Exception Execution Expected to Capture: Return fn (* args, ** kwargs) # Exception except you, specify: Logon (...) Return Cover < / Code>

and then you will call:

  reddis = reddisWrapper () reddis.do_someth ing (4)  
< P> It has not been tested, and works only with methods Will do For properties, you should catch the exception of the exception and give proper feedback.


Comments