For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Handling NotifyStore Errors



  • Hello, I am new to backtrader I'm currently working on handle errors from TWS
    I have created two variances of code which handles errors

    Variance #1

    def notify_store(self, msg, *args, **kwargs):
        if msg.errorCode == 502:
            print(msg.errorCode)
    

    This variance only works when the error exists for example if TWS is not running. If it is running it will produce an error

    AttributeError: 'ManagedAccounts' object has no attribute 'errorCode'
    

    Variance #2

    def notify_store(self, msg, *args, **kwargs):
        try:
                if msg.errorCode == 502:
                    print(msg.errorCode)
                   # Do Something to handle error 
            except AttributeError: # Error is not found
                print("No Error")
    

    Is there a better way to handle if the error doesn't exist? using Attribute Error feels too broad



  • you could check if msg has the attr set:

    if hasattr(msg, 'errorCode'):
        # check for error code
    


  • Awesome function, I didn't know this existed.

    is there any difference between these two designs?

     def notify_store(self, msg, *args, **kwargs):
            if hasattr(msg, 'errorCode'):
                if getattr(msg,'errorCode') == 502:
                        # Do Something
                        pass
    
    def notify_store(self, msg, *args, **kwargs):
            if hasattr(msg, 'errorCode'):
                if msg.errorCode == 502:
                    # Do Something
                    pass
    


  • getattr gives you more options. so you could do something like:

    error = getattr(msg, 'errorCode', False)
    

    which would prevent the AttributeError exception, if no errorCode is set. In that case, you will get False as the result.

    By accessing attributes directly, you would need to ensure, that the attribute you access is available or catch the AttributeError exception, so you know, the attribute is not set.

    With hasattr() you can check for the existance of a attribute.

    In your example, both solutions do the same.

    you could do also this:

     def notify_store(self, msg, *args, **kwargs):
            error = getattr(msg,'errorCode', False)
            if error:
                  # Do Something
    


  • @dasch Thank you.


Log in to reply
 

});