Catch “HTTPError 404” in python for gcloud commands

Trying to catch this error:

ERROR: (gcloud.compute.instances.add-labels) HTTPError 404: The resource 'projects/matei-testing-4010-5cbdeeff/zones/us-east1-b/instances/all' was not found

Tried different versions of code and none worked for me.

My current code does not seem to catch an error:

from googleapiclient import discovery, errors

try:
    print("Applying labels")
    gcloud_value = (f'gcloud compute instances add-labels all --labels="key=value" --zone=us-east1-b')
    process = subprocess.run([gcloud_value], shell=True)
except errors.HttpError:
   print("Command did not succeed because of the following error: {}".format(errors.HttpError))

How do I catch the error to use it later?

Thank you

Answer

Try this:-

import subprocess
gcloud_value = 'gcloud compute instances add-labels all --labels="key=value" --zone=us-east1-b'
process = subprocess.run(gcloud_value, shell=True, capture_output=True)
print(process.stdout.decode('utf-8'))
print(process.stderr.decode('utf-8'))
print(process.returncode)

One would expect gcloud to emit errors to stderr. Therefore by examining process.stderr you should be able to figure out what (if anything) has gone wrong. Also, if process.returncode is non-zero you should be able to deduce that it didn’t work but that depends entirely on how the underlying application (gcloud in this case) is written. There’s plenty of stuff out there that returns zero even when there was a failure!