Skip to main content Skip to footer

Search Crosser Knowledge Base

Custom Code modules with Try/Except

If you utilize custom code modules such as Python Bridge, IronPython, C Sharp or Java Script, keep in mind that your code becomes an essential part of the flow. Therefore, we highly recommend to introduce your code in a resilient way, i.e. using Try/Except clauses. Since Crosser has no control over your code you have to make sure by yourself that it can handle situations like “an expected property is not included in the incoming message” and similar situations.

Using Try/Except clauses is a good way of stabilizing custom code modules.

Example:

Below you see an example python code which calculates the sum of two values from an incoming message.

import json

def msg_handler(msg, module):
    # Extract value1 and value2 from the message
    value1 = msg['data']['value1']
    value2 = msg['data']['value2']   
    # Calculate the sum
    sum_value = value1 + value2    
    # Add the result to the message
    msg['data']['sum'] = sum_value    
    # Print the modified message for debugging
    print(json.dumps(msg))    
    # Pass the message to the next module
    module.next(msg)

Assuming one of the values is for some reason missing on the incoming message, the code will run into issues.

Therefore, we introduce try/except clauses for the msg_handler.

import json

def msg_handler(msg, module):
    try:
        # Extract the values from the message
        value1 = msg['data']['value1']
        value2 = msg['data']['value2']        
        # Calculate the sum
        result = value1 + value2        
        # Add the result to the message
        msg['data']['sum'] = result        
        # Print the modified message for debugging
        print(json.dumps(msg))  
        # Pass the message to the next module
        module.next(msg)
    except KeyError as e:
        print(f"KeyError: {e} - One of the required keys is missing in the incoming message.")
        module.next(msg)
    except TypeError as e:
        print(f"TypeError: {e} - Incoming values must be numbers.")
        module.next(msg)
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        module.next(msg)

About the author

David Nienhaus | Senior Solution Engineer

David is a Senior Solution Engineer at Crosser. He has over 10 years experience working with software integration and digitization projects for critical infrastructure.
His engineering background gives him the understanding and focus needed to solve customer use cases in the most efficient and successful way.