netbox-community / pynetbox

Python API client library for Netbox.
Apache License 2.0
538 stars 165 forks source link

I suspect that when filtering VLANS, the Exception is not Raised on an error message. #562

Closed MichaelPHolstein closed 10 months ago

MichaelPHolstein commented 10 months ago

Whe running the following code:

def read(netbox: api, debtor_code: str):
    try:
        return netbox.ipam.vlans.filter(tenant=debtor_code)
    except Exception as error:
        logging.exception(error)
        return None

I receive the following error message:

pynetbox.core.query.RequestError: The request failed with code 400 Bad Request: {'tenant': ['Select a valid choice. DB0001 is not one of the available choices.']}

I have a strong believe that the Exception is not raised.

markkuleinio commented 10 months ago

.filter() returns a RecordSet (a generator), which means that no HTTPS request has yet been made.

Possible RequestErrors happen only when you try to get some data from the generator:

>>> rs = netbox.ipam.vlans.filter(tenant="this is a string")
>>> type(rs)
<class 'pynetbox.core.response.RecordSet'>
>>> next(rs)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/dist-packages/pynetbox/core/response.py", line 117, in __next__
    next(self.response), self.endpoint.api, self.endpoint
  File "/usr/local/lib/python3.9/dist-packages/pynetbox/core/query.py", line 317, in get
    req = self._make_call(add_params=add_params)
  File "/usr/local/lib/python3.9/dist-packages/pynetbox/core/query.py", line 284, in _make_call
    raise RequestError(req)
pynetbox.core.query.RequestError: The request failed with code 400 Bad Request: {'tenant': ['Select a valid choice. this is a string is not one of the available choices.']}
>>>

If you need any possible exception to be raised right there, you can cast the RecordSet to a list:

        return list(netbox.ipam.vlans.filter(tenant=debtor_code))
MichaelPHolstein commented 10 months ago

Okay thank you for your reaction! Based on your post, I understand how to work with this. I will close the issue!