from typing import Union
from pathlib import Path


def try_rel_path(abs_path: Union[Path, str], ref_path: Union[Path, str]) -> Path:
    """Return ``abs_path`` relative to ``ref_path``, if possible."""
    try:
        return Path(abs_path).relative_to(ref_path)
    except ValueError as e:
        if "does not start with" in str(e):
            return Path(abs_path)
        raise ValueError(
            f"unexpected error while trying to return {abs_path} relative to {ref_path}"
        ) from e