Better way to structure and optimise try except statements I am new to python and I am trying to write a function with various actions based on the parameters sent. I am checking if the data has valid format then it publishes to /accepted otherwise to /rejected. If the data is fine then it does the function and then publishes to /success otherwise to /failure
Here is what i am doing now -
def data_handler(event, context):
    try:
        input_topic = context.topic
        input_message = event
        response = f'Invoked on topic {input_topic} with message {input_message}'
        logging.info(response)
        client.publish(topic=input_topic + '/accepted', payload=json.dumps({'state': 'accepted'}))
    except Exception as e:
        logging.error(e)
        client.publish(topic=input_topic + '/rejected', payload=json.dumps({'state': 'rejected'}))

    try:
        print('Perform the function based on input message')
        client.publish(topic=input_topic + '/success', payload=json.dumps({'state': 'Execution succeeded'}))
    except Exception as e:
        logging.error(e)
        client.publish(topic=input_topic + '/failure', payload=json.dumps({'state': 'Execution failed'}))

This works as of now but i think there should be a better way to implement this. Any idea?
Given that there isn't much here to analyse purely based on performance since we don't know what those other function calls do, here are some minor changes:
def data_handler(message, topic):
    try:
        logging.debug(f'Invoked on topic {topic} with message {message}')
        client.publish(topic=topic + '/pass', payload=json.dumps({'state': 'pass'}))
    except Exception as e:
        logging.error(e)
        client.publish(topic=topic + '/fail', payload=json.dumps({'state': 'fail'}))

Both try/catch blocks in your code look identical, and you should have only one endpoint that needs to be communicated with. If you really need both, then there should be a separate function to have this code.
It also seems pretty redundant that you're publishing to a pass and fail endpoint and have a payload that says whether or not it passed or failed. You should know that status based on the endpoint that receives the message.
You can have the payload be more descriptive as well to remove multiple endpoints. Something like {'formatted': true, 'error': ''} is far more informative.
Lastly, you can just pass your one-off variables into this function, like so: data_handler(event, context.topic). If your event really is just a post message and not a posting event object, then that should be clarified somewhere in the code base.