'How can I capture the error thrown by a python script in the bash script calling it?

I want to write a bash script that sends a message depending on whether a python script it called ran successfully or threw an error.

In the case that it throws an error, I want to add the error message to the sent text.

Currently, I have this:

if python3 this_should_fail.py; then
    curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script finished running ✅"}' \
        $WEBHOOK_URL
else
    curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script failed with an error ❌"}' \
        $WEBHOOK_URL
fi

How do I capture the error message thrown by this_should_fail.py and include it in the sent JSON as a string?

I am looking for something like

curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script failed with an error ❌",
             "error_message": '$ESCAPED_ERROR_MESSAGE_STRING_HERE'}' \
        $WEBHOOK_URL

The error message I want to capture is, for example:

Traceback (most recent call last):
  File "this_should_fail.py", line 5, in <module>
    a = 100 / 0
ZeroDivisionError: division by zero


Solution 1:[1]

You can probably do something like this depending on how your webhook is expecting the data

err=$(mktemp)
if python3 this_should_fail.py 2>"$err"; then
    curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script finished running ?"}' \
        $WEBHOOK_URL
else
    curl \
        -H 'Content-Type: application/json' \
        -d '{"text": "Your script failed with an error ?"}' \
        --data-binary "@$err" \
        $WEBHOOK_URL
fi

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Diego Torres Milano