1

I want to build my application with a redis cache. but maybe redis is not available all the time in our case,
so I hope, it redis works well, we use it. if it can't work, just logging and ignore it this time.

for example:

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

since there are many place I will run some conn.{rediscommand}, I don't like to use try/except every place.

so the solution maybe :

class softcache(redis.StrictRedis):
   def sadd(key, *p):
       try:
          super(redis.StrictRedis, self).sadd(key, p)
       except:
          ..

but since redis have many commands, I have to warp them one by one.

is it possible to custom a exception handler for a class to handle all the exceptions which come from this class ?

5
  • 1
    take a look at Exceptions for the whole class. you may use decorator or dispatcher as suggested. Commented Feb 18, 2014 at 12:28
  • 1
    The syntax is try: ... except: ... Commented Feb 18, 2014 at 12:28
  • That's what context managers are for. Commented Feb 18, 2014 at 12:40
  • @Bakuriu the problem with context manager is that you have to write a with block each time you do a function call. I think a wrapper/proxy would be more useful (within the mistake of catching everything...) Commented Feb 18, 2014 at 13:26
  • @ikaros45 I don't think it is a problem. If the function is defined in a library you do not want to modify it just to avoid typing a with. If someone else reads your code he wont understand what the hell is happening. If the function is defined by you, surely using a decorator to add exception handling might be better. Commented Feb 18, 2014 at 13:48

2 Answers 2

1

Silencing per default all exceptions is probably the worst thing you can do.

Anyway, for your problem you can write a generic wrapper that just redirects to the connection object.

class ReddisWrapper(object):

    conn = conn # Here your reddis object

    def __getattr__(self, attr):

         def wrapper(*args, **kwargs):
             # Get the real reddis function
             fn = getattr(self.conn, attr)

             # Execute the function catching exceptions
             try:
                  return fn(*args, **kwargs)

             # Specify here the exceptions you expect                 
             except:
                  log(...)

         return wrapper

And then you would call like this:

reddis = ReddisWrapper()
reddis.do_something(4)

This has not been tested, and will only work with methods. For properties you should catch the non callable exception and react properly.

Sign up to request clarification or add additional context in comments.

6 Comments

hi ikaros45, your suggestion is easiest understand by me. but seems not works. ` class X(object): def p(self, a): print(a) raise '1' class WX(object): x = X() def __getattr__(self, item, *args, **kwargs): print args fn = getattr(self.x, item) print("fn", fn) try: fn(args) except: print("get Exception") wx = WX() wx.p('abc') print "ok" `
hi ikaros45, thanks for suggestion. it works now with the following code. def __getattr__(self, attr): if hasattr(self.__conn, attr): def wapper(*args, **kw): fn = getattr(self.__conn, attr) try: return fn(*args, **kw) except redis.exceptions.ConnectionError: pass return wapper raise AttributeError()
can you modify your answer so that I can accept your answer. I learnt much from your suggestion. Thank you!
@zhihuifan, I'm happy to help but I don't understand the code you posted in the comments.
if you try your suggestion, you will found getattr only accept 2 arguments, not 4. in my comment, getattr return a pointer to function wapper, wapper accept these parameters, that works.
|
0

Is it always the same Exception?

If so you could write a custom, Exception catching and logging decorator.

Something like the following:

def exception_catcher(fn):
    try:
        fn()
    except Exception as e:
        log(e)

Then just use it around your code:

@exception_catcher
sadd('s', *array)

The comment and link to Exceptions for the whole class suggested by @idanshmu will offer more detailed handling of different Exceptions per method.

2 Comments

hi Ewan, it is not the same exception. BTW, where can I find the whole list @xxxx python support ?
hi Ewan, it should be the same exception. understand your suggestion now. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.