zExceptions
zExceptions is a Python library containing common exceptions used primarily within the Zope and Plone web frameworks. It provides specialized exceptions like `NotFound`, `Redirect`, `Unauthorized`, and `Forbidden` that map to HTTP status codes, simplifying error handling in Zope applications. The current version is 6.0, and it follows an infrequent release cadence, often aligning with Zope framework updates.
Common errors
-
ModuleNotFoundError: No module named 'zexceptions'
cause The `zexceptions` library is not installed in the current Python environment.fixInstall the library using pip: `pip install zexceptions` -
ImportError: cannot import name 'HTTPExceptionHandler' from 'zexceptions' (path/to/site-packages/zexceptions/__init__.py)
cause The `HTTPExceptionHandler` class was removed in `zexceptions` version 5.0. Your code is attempting to import a deprecated component after upgrading to `zexceptions` 5.0 or newer.fixRemove or refactor code that imports `HTTPExceptionHandler`. This class is no longer part of the library. Consult Zope/Plone documentation for modern exception handling. -
TypeError: 'NotFound' object is not iterable
cause Misusing a `zexceptions` instance (e.g., `NotFound()`) as if it were a data structure or iterable, instead of raising it as an exception.fixEnsure `zexceptions` are raised using `raise NotFound(...)` and then caught in an `except NotFound:` block. Do not attempt to iterate over them or call methods not related to standard exception handling.
Warnings
- breaking zexceptions version 6.0 requires Python 3.10 or newer.
- breaking The `HTTPExceptionHandler` class was removed in `zexceptions` 5.0.
- gotcha Using zexceptions outside of a Zope or Plone framework context.
Install
-
pip install zexceptions
Imports
- NotFound
from zexceptions import NotFound
- Redirect
from zexceptions import Redirect
- Unauthorized
from zexceptions import Unauthorized
- Forbidden
from zexceptions import Forbidden
Quickstart
from zexceptions import NotFound, Unauthorized, Redirect
def get_resource(resource_id: str, is_authenticated: bool):
if resource_id == "non_existent":
raise NotFound("The requested resource was not found.")
elif resource_id == "private" and not is_authenticated:
raise Unauthorized("Authentication required to access this resource.")
elif resource_id == "old_path":
# Redirect to a new path with a 301 status code
raise Redirect(location="/new_path_for_old_resource", code=301)
return f"Resource {resource_id} data."
# Example Usage:
try:
print(get_resource("some_item", True))
print(get_resource("private", False))
except NotFound as e:
print(f"Caught NotFound: {e}")
except Unauthorized as e:
print(f"Caught Unauthorized: {e}")
except Redirect as e:
print(f"Caught Redirect: {e.location} with code {e.code}")
try:
get_resource("non_existent", True)
except NotFound as e:
print(f"Caught NotFound (again): {e}")