0

I'm trying to figure out how to write multiple exceptions for an IPAM API, which means that when one prefix is full, it should take the next one. this works with one, but not with several different:

dict_endpoints = {"vpn-1": 9,
                  "vpn-2": 67,
                  "vpn-3": 68,
                  "vpn-4": 69}

def api(var_endpoint):
    url = "https://myURL.org/"
    token = os.environ['NETBOXTOKEN']
    nb = pynetbox.api(url=url, token=token)
    prefix = nb.ipam.prefixes.get(var_endpoint)
    new_prefix = prefix.available_prefixes.create({"prefix_length": 48})
    print(new_prefix)

try:
    api(dict_endpoints["vpn-1"])
except:
    api(dict_endpoints["vpn-2"])
# multiple exceptions without exiting the script
#except:
#    api(dict_endpoints["vpn-3"])
1
  • Do you mean you want to catch exceptions from inside the except block? You could do that with a new try catch block inside it. This dosen't work because both those excepts are for catching errors from the same try block the second except dosen't catch things from the first except. Commented Aug 8, 2022 at 11:45

2 Answers 2

2

You could create a loop:

for endpoint in dict_endpoints.values():
    try:
        api(endpoint)
        break  # success!!
    except:
        pass  # ignore error and go to next iteration
else:  # all failed :-(
    print("all endpoints failed...")
Sign up to request clarification or add additional context in comments.

Comments

1

You can use else statement or handle multiple excepts like this:

try:
  --snip--
except (exception_1, exception_2):
  --snip--
else:
  --snip--

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.