Skip to content

prefect.exceptions

Prefect-specific exceptions.

Abort

Bases: PrefectSignal

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

Indicates that the run should exit immediately.

Source code in src/prefect/exceptions.py
294
295
296
297
298
299
class Abort(PrefectSignal):
    """
    Raised when the API sends an 'ABORT' instruction during state proposal.

    Indicates that the run should exit immediately.
    """

BlockMissingCapabilities

Bases: PrefectException

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

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

CancelledRun

Bases: PrefectException

Raised when the result from a cancelled run is retrieved and an exception is not attached.

This occurs when a string is attached to the state instead of an exception or if the state's data is null.

Source code in src/prefect/exceptions.py
79
80
81
82
83
84
85
86
class CancelledRun(PrefectException):
    """
    Raised when the result from a cancelled run is retrieved and an exception
    is not attached.

    This occurs when a string is attached to the state instead of an exception
    or if the state's data is null.
    """

ConfigurationError

Bases: PrefectException

Raised when a configuration is invalid.

Source code in src/prefect/exceptions.py
433
434
435
436
class ConfigurationError(PrefectException):
    """
    Raised when a configuration is invalid.
    """

CrashedRun

Bases: PrefectException

Raised when the result from a crashed run is retrieved.

This occurs when a string is attached to the state instead of an exception or if the state's data is null.

Source code in src/prefect/exceptions.py
60
61
62
63
64
65
66
class CrashedRun(PrefectException):
    """
    Raised when the result from a crashed run is retrieved.

    This occurs when a string is attached to the state instead of an exception or if
    the state's data is null.
    """

ExternalSignal

Bases: BaseException

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

Source code in src/prefect/exceptions.py
312
313
314
315
class ExternalSignal(BaseException):
    """
    Base type for external signal-like exceptions that should never be caught by users.
    """

FailedRun

Bases: PrefectException

Raised when the result from a failed run is retrieved and an exception is not attached.

This occurs when a string is attached to the state instead of an exception or if the state's data is null.

Source code in src/prefect/exceptions.py
69
70
71
72
73
74
75
76
class FailedRun(PrefectException):
    """
    Raised when the result from a failed run is retrieved and an exception is not
    attached.

    This occurs when a string is attached to the state instead of an exception or if
    the state's data is null.
    """

FlowPauseTimeout

Bases: PrefectException

Raised when a flow pause times out

Source code in src/prefect/exceptions.py
410
411
class FlowPauseTimeout(PrefectException):
    """Raised when a flow pause times out"""

FlowRunWaitTimeout

Bases: PrefectException

Raised when a flow run takes longer than a given timeout

Source code in src/prefect/exceptions.py
414
415
class FlowRunWaitTimeout(PrefectException):
    """Raised when a flow run takes longer than a given timeout"""

FlowScriptError

Bases: PrefectException

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

Source code in src/prefect/exceptions.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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)

InfrastructureError

Bases: PrefectException

A base class for exceptions related to infrastructure blocks

Source code in src/prefect/exceptions.py
386
387
388
389
class InfrastructureError(PrefectException):
    """
    A base class for exceptions related to infrastructure blocks
    """

InfrastructureNotAvailable

Bases: PrefectException

Raised when infrastructure is not accessible from the current machine. For example, if a process was spawned on another machine it cannot be managed.

Source code in src/prefect/exceptions.py
399
400
401
402
403
class InfrastructureNotAvailable(PrefectException):
    """
    Raised when infrastructure is not accessible from the current machine. For example,
    if a process was spawned on another machine it cannot be managed.
    """

InfrastructureNotFound

Bases: PrefectException

Raised when infrastructure is missing, likely because it has exited or been deleted.

Source code in src/prefect/exceptions.py
392
393
394
395
396
class InfrastructureNotFound(PrefectException):
    """
    Raised when infrastructure is missing, likely because it has exited or been
    deleted.
    """

InvalidNameError

Bases: PrefectException, ValueError

Raised when a name contains characters that are not permitted.

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

InvalidRepositoryURLError

Bases: PrefectException

Raised when an incorrect URL is provided to a GitHub filesystem block.

Source code in src/prefect/exceptions.py
382
383
class InvalidRepositoryURLError(PrefectException):
    """Raised when an incorrect URL is provided to a GitHub filesystem block."""

MappingLengthMismatch

Bases: PrefectException

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

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

MappingMissingIterable

Bases: PrefectException

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

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

MissingContextError

Bases: PrefectException, RuntimeError

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 src/prefect/exceptions.py
262
263
264
265
266
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

Bases: PrefectException

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

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

MissingProfileError

Bases: PrefectException, ValueError

Raised when a profile name does not exist.

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

MissingResult

Bases: PrefectException

Raised when a result is missing from a state; often when result persistence is disabled and the state is retrieved from the API.

Source code in src/prefect/exceptions.py
119
120
121
122
123
class MissingResult(PrefectException):
    """
    Raised when a result is missing from a state; often when result persistence is
    disabled and the state is retrieved from the API.
    """

NotPausedError

Bases: PrefectException

Raised when attempting to unpause a run that isn't paused.

Source code in src/prefect/exceptions.py
406
407
class NotPausedError(PrefectException):
    """Raised when attempting to unpause a run that isn't paused."""

ObjectAlreadyExists

Bases: PrefectException

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

Source code in src/prefect/exceptions.py
245
246
247
248
249
250
251
252
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

Bases: PrefectException

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

Source code in src/prefect/exceptions.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
class ObjectNotFound(PrefectException):
    """
    Raised when the client receives a 404 (not found) from the API.
    """

    def __init__(
        self,
        http_exc: Exception,
        help_message: Optional[str] = None,
        *args,
        **kwargs,
    ):
        self.http_exc = http_exc
        self.help_message = help_message
        super().__init__(help_message, *args, **kwargs)

    def __str__(self):
        return self.help_message or super().__str__()

ParameterBindError

Bases: TypeError, PrefectException

Raised when args and kwargs cannot be converted to parameters.

Source code in src/prefect/exceptions.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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: {list(call_kwargs.keys())}"
        msg = f"{base}.\n{signature} but {received}."
        return cls(msg)

ParameterTypeError

Bases: PrefectException

Raised when a parameter does not pass Pydantic type validation.

Source code in src/prefect/exceptions.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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: ValidationError) -> Self:
        bad_params = [
            f'{".".join(str(item) for item in err["loc"])}: {err["msg"]}'
            for err in exc.errors()
        ]
        msg = "Flow run received invalid parameters:\n - " + "\n - ".join(bad_params)
        return cls(msg)

Pause

Bases: PrefectSignal

Raised when a flow run is PAUSED and needs to exit for resubmission.

Source code in src/prefect/exceptions.py
302
303
304
305
306
307
308
309
class Pause(PrefectSignal):
    """
    Raised when a flow run is PAUSED and needs to exit for resubmission.
    """

    def __init__(self, *args, state=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.state = state

PausedRun

Bases: PrefectException

Raised when the result from a paused run is retrieved.

Source code in src/prefect/exceptions.py
89
90
91
92
93
94
95
96
class PausedRun(PrefectException):
    """
    Raised when the result from a paused run is retrieved.
    """

    def __init__(self, *args, state=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.state = state

PrefectException

Bases: Exception

Base exception type for Prefect errors.

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

PrefectHTTPStatusError

Bases: 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.

Source code in src/prefect/exceptions.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
        )

from_httpx_error(httpx_error) classmethod

Generate a PrefectHTTPStatusError from an httpx.HTTPStatusError.

Source code in src/prefect/exceptions.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
@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
    )

PrefectImportError

Bases: ImportError

An error raised when a Prefect object cannot be imported due to a move or removal.

Source code in src/prefect/exceptions.py
418
419
420
421
422
423
424
class PrefectImportError(ImportError):
    """
    An error raised when a Prefect object cannot be imported due to a move or removal.
    """

    def __init__(self, message: str) -> None:
        super().__init__(message)

PrefectSignal

Bases: BaseException

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

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

ProfileSettingsValidationError

Bases: PrefectException

Raised when a profile settings are invalid.

Source code in src/prefect/exceptions.py
439
440
441
442
443
444
445
class ProfileSettingsValidationError(PrefectException):
    """
    Raised when a profile settings are invalid.
    """

    def __init__(self, errors: List[Tuple[Any, ValidationError]]) -> None:
        self.errors = errors

ProtectedBlockError

Bases: PrefectException

Raised when an operation is prevented due to block protection.

Source code in src/prefect/exceptions.py
376
377
378
379
class ProtectedBlockError(PrefectException):
    """
    Raised when an operation is prevented due to block protection.
    """

ReservedArgumentError

Bases: PrefectException, TypeError

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

Source code in src/prefect/exceptions.py
275
276
277
278
279
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

Bases: PrefectException

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

Source code in src/prefect/exceptions.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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: {user_exc!r}"
        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],
        )

SerializationError

Bases: PrefectException

Raised when an object cannot be serialized.

Source code in src/prefect/exceptions.py
427
428
429
430
class SerializationError(PrefectException):
    """
    Raised when an object cannot be serialized.
    """

SignatureMismatchError

Bases: PrefectException, TypeError

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

Source code in src/prefect/exceptions.py
210
211
212
213
214
215
216
217
218
219
220
221
222
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"
            f" parameters {provided_params}"
        )
        return cls(msg)

TerminationSignal

Bases: ExternalSignal

Raised when a flow run receives a termination signal.

Source code in src/prefect/exceptions.py
318
319
320
321
322
323
324
class TerminationSignal(ExternalSignal):
    """
    Raised when a flow run receives a termination signal.
    """

    def __init__(self, signal: int):
        self.signal = signal

UnfinishedRun

Bases: PrefectException

Raised when the result from a run that is not finished is retrieved.

For example, if a run is in a SCHEDULED, PENDING, CANCELLING, or RUNNING state.

Source code in src/prefect/exceptions.py
 99
100
101
102
103
104
class UnfinishedRun(PrefectException):
    """
    Raised when the result from a run that is not finished is retrieved.

    For example, if a run is in a SCHEDULED, PENDING, CANCELLING, or RUNNING state.
    """

UnspecifiedFlowError

Bases: PrefectException

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

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

UpstreamTaskError

Bases: PrefectException

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

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

exception_traceback(exc)

Convert an exception to a printable string with a traceback

Source code in src/prefect/exceptions.py
46
47
48
49
50
51
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()))