Skip to content

prefect.exceptions

Prefect-specific exceptions.

Abort

Raised when the API sends an 'ABORT' instruction during state proposal.

Indicates that the run should exit immediately.

Source code in prefect/exceptions.py
class Abort(PrefectSignal):
    """
    Raised when the API sends an 'ABORT' instruction during state proposal.

    Indicates that the run should exit immediately.
    """

BlockMissingCapabilities

Raised when a block does not have required capabilities for a given operation.

Source code in prefect/exceptions.py
class BlockMissingCapabilities(PrefectException):
    """
    Raised when a block does not have required capabilities for a given operation.
    """

FlowScriptError

Raised when a script errors during evaluation while attempting to load a flow.

Source code in prefect/exceptions.py
class FlowScriptError(PrefectException):
    """
    Raised when a script errors during evaluation while attempting to load a flow.
    """

    def __init__(
        self,
        user_exc: Exception,
        script_path: str,
    ) -> None:
        message = f"Flow script at {script_path!r} encountered an exception"
        super().__init__(message)

        self.user_exc = user_exc

    def rich_user_traceback(self, **kwargs):
        trace = Traceback.extract(
            type(self.user_exc),
            self.user_exc,
            self.user_exc.__traceback__.tb_next.tb_next.tb_next.tb_next,
        )
        return Traceback(trace, **kwargs)

InvalidNameError

Raised when a name contains characters that are not permitted.

Source code in prefect/exceptions.py
class InvalidNameError(PrefectException, ValueError):
    """
    Raised when a name contains characters that are not permitted.
    """

MappingLengthMismatch

Raised when attempting to call Task.map with arguments of different lengths.

Source code in prefect/exceptions.py
class MappingLengthMismatch(PrefectException):
    """
    Raised when attempting to call Task.map with arguments of different lengths.
    """

MappingMissingIterable

Raised when attempting to call Task.map with all static arguments

Source code in prefect/exceptions.py
class MappingMissingIterable(PrefectException):
    """
    Raised when attempting to call Task.map with all static arguments
    """

MissingContextError

Raised when a method is called that requires a task or flow run context to be active but one cannot be found.

Source code in prefect/exceptions.py
class MissingContextError(PrefectException, RuntimeError):
    """
    Raised when a method is called that requires a task or flow run context to be
    active but one cannot be found.
    """

MissingFlowError

Raised when a given flow name is not found in the expected script.

Source code in prefect/exceptions.py
class MissingFlowError(PrefectException):
    """
    Raised when a given flow name is not found in the expected script.
    """

MissingProfileError

Raised when a profile name does not exist.

Source code in prefect/exceptions.py
class MissingProfileError(PrefectException, ValueError):
    """
    Raised when a profile name does not exist.
    """

ObjectAlreadyExists

Raised when the client receives a 409 (conflict) from the API.

Source code in prefect/exceptions.py
class ObjectAlreadyExists(PrefectException):
    """
    Raised when the client receives a 409 (conflict) from the API.
    """

    def __init__(self, http_exc: Exception, *args, **kwargs):
        self.http_exc = http_exc
        super().__init__(*args, **kwargs)

ObjectNotFound

Raised when the client receives a 404 (not found) from the API.

Source code in prefect/exceptions.py
class ObjectNotFound(PrefectException):
    """
    Raised when the client receives a 404 (not found) from the API.
    """

    def __init__(self, http_exc: Exception, *args, **kwargs):
        self.http_exc = http_exc
        super().__init__(*args, **kwargs)

ParameterBindError

Raised when args and kwargs cannot be converted to parameters.

Source code in prefect/exceptions.py
class ParameterBindError(TypeError, PrefectException):
    """
    Raised when args and kwargs cannot be converted to parameters.
    """

    def __init__(self, msg: str):
        super().__init__(msg)

    @classmethod
    def from_bind_failure(
        cls, fn: Callable, exc: TypeError, call_args: List, call_kwargs: Dict
    ) -> Self:
        fn_signature = str(inspect.signature(fn)).strip("()")

        base = f"Error binding parameters for function '{fn.__name__}': {exc}"
        signature = f"Function '{fn.__name__}' has signature '{fn_signature}'"
        received = f"received args: {call_args} and kwargs: {call_kwargs}"
        msg = f"{base}.\n{signature} but {received}."
        return cls(msg)

ParameterTypeError

Raised when a parameter does not pass Pydantic type validation.

Source code in prefect/exceptions.py
class ParameterTypeError(PrefectException):
    """
    Raised when a parameter does not pass Pydantic type validation.
    """

    def __init__(self, msg: str):
        super().__init__(msg)

    @classmethod
    def from_validation_error(cls, exc: pydantic.ValidationError) -> Self:
        bad_params = [f'{err["loc"][0]}: {err["msg"]}' for err in exc.errors()]
        msg = "Flow run received invalid parameters:\n - " + "\n - ".join(bad_params)
        return cls(msg)

PrefectException

Base exception type for Prefect errors.

Source code in prefect/exceptions.py
class PrefectException(Exception):
    """
    Base exception type for Prefect errors.
    """

PrefectHTTPStatusError

Raised when client receives a Response that contains an HTTPStatusError.

Used to include API error details in the error messages that the client provides users.

Source code in prefect/exceptions.py
class PrefectHTTPStatusError(HTTPStatusError):
    """
    Raised when client receives a `Response` that contains an HTTPStatusError.

    Used to include API error details in the error messages that the client provides users.
    """

    @classmethod
    def from_httpx_error(cls: Type[Self], httpx_error: HTTPStatusError) -> Self:
        """
        Generate a `PrefectHTTPStatusError` from an `httpx.HTTPStatusError`.
        """
        try:
            details = httpx_error.response.json()
        except Exception:
            details = None

        error_message, *more_info = str(httpx_error).split("\n")

        if details:
            message_components = [error_message, f"Response: {details}", *more_info]
        else:
            message_components = [error_message, *more_info]

        new_message = "\n".join(message_components)

        return cls(
            new_message, request=httpx_error.request, response=httpx_error.response
        )

PrefectHTTPStatusError.from_httpx_error classmethod

Generate a PrefectHTTPStatusError from an httpx.HTTPStatusError.

Source code in prefect/exceptions.py
@classmethod
def from_httpx_error(cls: Type[Self], httpx_error: HTTPStatusError) -> Self:
    """
    Generate a `PrefectHTTPStatusError` from an `httpx.HTTPStatusError`.
    """
    try:
        details = httpx_error.response.json()
    except Exception:
        details = None

    error_message, *more_info = str(httpx_error).split("\n")

    if details:
        message_components = [error_message, f"Response: {details}", *more_info]
    else:
        message_components = [error_message, *more_info]

    new_message = "\n".join(message_components)

    return cls(
        new_message, request=httpx_error.request, response=httpx_error.response
    )

PrefectSignal

Base type for signal-like exceptions that should never be caught by users.

Source code in prefect/exceptions.py
class PrefectSignal(BaseException):
    """
    Base type for signal-like exceptions that should never be caught by users.
    """

ReservedArgumentError

Raised when a function used with Prefect has an argument with a name that is reserved for a Prefect feature

Source code in prefect/exceptions.py
class ReservedArgumentError(PrefectException, TypeError):
    """
    Raised when a function used with Prefect has an argument with a name that is
    reserved for a Prefect feature
    """

ScriptError

Raised when a script errors during evaluation while attempting to load data

Source code in prefect/exceptions.py
class ScriptError(PrefectException):
    """
    Raised when a script errors during evaluation while attempting to load data
    """

    def __init__(
        self,
        user_exc: Exception,
        path: str,
    ) -> None:
        message = f"Script at {str(path)!r} encountered an exception"
        super().__init__(message)
        self.user_exc = user_exc

        # Strip script run information from the traceback
        self.user_exc.__traceback__ = _trim_traceback(
            self.user_exc.__traceback__,
            remove_modules=[prefect.utilities.importtools],
        )

SignatureMismatchError

Raised when parameters passed to a function do not match its signature.

Source code in prefect/exceptions.py
class SignatureMismatchError(PrefectException, TypeError):
    """Raised when parameters passed to a function do not match its signature."""

    def __init__(self, msg: str):
        super().__init__(msg)

    @classmethod
    def from_bad_params(cls, expected_params: List[str], provided_params: List[str]):
        msg = f"Function expects parameters {expected_params} but was provided with parameters {provided_params}"
        return cls(msg)

UnspecifiedFlowError

Raised when multiple flows are found in the expected script and no name is given.

Source code in prefect/exceptions.py
class UnspecifiedFlowError(PrefectException):
    """
    Raised when multiple flows are found in the expected script and no name is given.
    """

UpstreamTaskError

Raised when a task relies on the result of another task but that task is not 'COMPLETE'

Source code in prefect/exceptions.py
class UpstreamTaskError(PrefectException):
    """
    Raised when a task relies on the result of another task but that task is not
    'COMPLETE'
    """

exception_traceback

Convert an exception to a printable string with a traceback

Source code in prefect/exceptions.py
def exception_traceback(exc: Exception) -> str:
    """
    Convert an exception to a printable string with a traceback
    """
    tb = traceback.TracebackException.from_exception(exc)
    return "".join(list(tb.format()))