Skip to content

feat: Add common exceptions and map_exception helper#42

Merged
kylebarron merged 1 commit into
mainfrom
kyle/common-exceptions
Jun 13, 2025
Merged

feat: Add common exceptions and map_exception helper#42
kylebarron merged 1 commit into
mainfrom
kyle/common-exceptions

Conversation

@kylebarron

@kylebarron kylebarron commented Jun 13, 2025

Copy link
Copy Markdown
Member

@geospatial-jeff

Users writing generic code with obspec may wish to catch common exceptions. For example,
a user might wish to perform a head request but allow for the case where the object does
not exist.

Common exceptions pose a challenge for obspec. In general obspec strives to use
structural subtyping (protocols) rather than nominal subtyping
(subclassing)
. This is because protocols allow for implementations to
have no knowledge of or dependency on a shared base library (obspec) while still being
able to use the same interface.

However, structural subtyping does not work for exceptions: when you use except Exception, that uses an isinstance check under the hood.

As a workaround, we define well-known names for exceptions and expect external
implementations to use the same names.

Obspec users

Use the [map_exception][obspec.exceptions.map_exception] function in this module to
convert from an implementation-defined exception to an obspec-defined exception.

from obspec import Head
from obspec.exceptions import NotFoundError, map_exception


def check_if_exists(client: Head, path: str) -> bool:
    \"\"\"Check if a file exists at the given location.

    Returns True if the file exists, False otherwise.
    \"\"\"
    try:
        client.head(path)
    except Exception as e:
        if isinstance(map_exception(e), NotFoundError):
            return False

        raise

    return True

!!! note
If you don't care about catching exceptions, you can ignore this module entirely.

Obspec implementors

Create your own exceptions but ensure you use the same names for your own exceptions
as defined in this module.

You may also have other exceptions that are not defined here, but any exceptions that
logically fall under the purview of the exceptions defined here should your exceptions
with the same name.

@kylebarron kylebarron merged commit 21ef0ce into main Jun 13, 2025
5 checks passed
@kylebarron kylebarron deleted the kyle/common-exceptions branch June 13, 2025 19:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant