WorkflowsException: Structured Error Handling

Workflows provides a structured exception system through WorkflowsException for consistent error handling across workflows and activities.

Overview

Overview

WorkflowsException is the standard exception class for handling errors in workflows. It provides:

  • Structured error codes via ErrorCode enum
  • HTTP status code mapping
  • Serialization to JSON responses
  • Factory methods for common error scenarios
Basic usage

Basic usage

import asyncio
import http
import mistralai.workflows as workflows
from mistralai.workflows.exceptions import WorkflowsException, ErrorCode
from pydantic import BaseModel


@workflows.activity()
async def validate_input(value: str) -> str:
    if not value:
        raise WorkflowsException(
            code=ErrorCode.INVALID_ARGUMENTS_ERROR,
            message="Input value cannot be empty",
            status=http.HTTPStatus.BAD_REQUEST,
        )
    return f"valid:{value}"


class Input(BaseModel):
    value: str


@workflows.workflow.define(name="exception_workflow")
class ExceptionWorkflow:
    @workflows.workflow.entrypoint
    async def run(self, params: Input) -> str:
        return await validate_input(params.value)


async def main():
    result = await workflows.execute_workflow(
        ExceptionWorkflow,
        params=Input(value="hello"),
    )
    print(result)

    try:
        await workflows.execute_workflow(
            ExceptionWorkflow,
            params=Input(value=""),
        )
    except WorkflowsException as e:
        print(f"code:    {e.code}")
        print(f"message: {e.message}")
        print(f"status:  {e.status}")
Constructor Parameters

Constructor Parameters

ParameterTypeDefaultDescription
messagestrrequiredHuman-readable error message
statusHTTPStatusINTERNAL_SERVER_ERRORHTTP status code
codeErrorCodeEXECUTION_ERRORStructured error code
typestr"invalid_request_error"Error type string
Error Codes

Error Codes

The ErrorCode enum provides structured error codes organized by category:

General Errors (40**)

CodeDescription
execution_errorGeneral execution error
platform_errorPlatform-related error
platform_service_errorPlatform service error
platform_connection_errorConnection to platform failed
platform_client_creation_errorFailed to create platform client
search_attributes_creation_errorFailed to create search attributes

Activity Errors (41**)

CodeDescription
activity_definition_errorActivity incorrectly defined
activity_not_found_errorActivity not found
invalid_arguments_errorInvalid arguments provided
activity_not_module_levelActivity must be at module level
tool_argument_errorTool argument error
rate_limit_errorRate limit exceeded

Workflow Errors (42**)

CodeDescription
workflow_definition_errorWorkflow incorrectly defined
workflow_description_errorWorkflow description error
workflow_already_startedWorkflow already running
workflow_not_foundWorkflow not found
invalid_params_errorInvalid parameters
workflow_timeout_errorWorkflow timed out
workflow_signal_definition_errorSignal incorrectly defined
workflow_update_definition_errorUpdate incorrectly defined
workflow_query_errorFail to query a workflow

Worker Errors (43**)

CodeDescription
worker_registration_errorWorker registration failed
worker_runtime_config_errorWorker runtime configuration error

Durable Agent Errors (44**)

CodeDescription
agent_execution_errorAgent Execution Error

Infrastructure Errors (45**)

CodeDescription
workspace_already_usedWorkspace already in use
in_memory_cache_errorIn-memory cache error
rejected_query_errorQuery was rejected
unserializable_payload_errorPayload cannot be serialized
blob_storage_config_errorBlob storage configuration error

API Endpoint Errors (46**)

The following error codes are used to identify specific errors that can occur when interacting with the workflow API. These codes follow the {HTTP_METHOD}_{ENDPOINT}_ERROR naming convention and are returned in the code field of error responses.

CodeDescription
get_workflows_errorError when retrieving workflows
get_workflows_versions_errorError when retrieving workflow versions
get_workers_whoami_errorError when retrieving worker identity
post_workflows_register_errorError when registering a workflow
post_workflows_execute_errorError when executing a workflow
post_executions_terminate_errorError when terminating an execution
get_executions_errorError when retrieving executions
get_executions_trace_otel_errorError when retrieving execution OTEL trace
get_executions_trace_summary_errorError when retrieving execution trace summary
get_executions_trace_events_errorError when retrieving execution trace events
post_executions_signals_errorError when sending a signal to an execution
post_executions_queries_errorError when querying an execution
post_executions_updates_errorError when updating an execution
post_schedules_errorError when creating a schedule
delete_schedules_errorError when deleting a schedule
get_schedules_errorError when retrieving schedules
post_executions_stream_errorError when streaming execution results
get_events_stream_errorError when streaming events
post_events_errorError when posting events
Exception Properties and Methods

Exception Properties and Methods

from_platform_error()

Create an exception from platform errors:

try:
    await client.workflows.execute_workflow_async(...)
except Exception as e:
    raise WorkflowsException.from_platform_error(
        error=e,
        message_override="Failed to execute workflow",
        status_override=HTTPStatus.SERVICE_UNAVAILABLE
    )

Handles specific error types:

  • RPCError → Maps to appropriate error code based on RPC status
  • WorkflowQueryRejectedErrorREJECTED_QUERY_ERROR
  • WorkflowAlreadyStartedErrorWORKFLOW_ALREADY_STARTED

from_api_client_error()

Create an exception from HTTP client errors:

import httpx

try:
    response = await client.get("https://api.example.com")
except httpx.HTTPError as e:
    raise WorkflowsException.from_api_client_error(
        exc=e,
        message="External API call failed",
        code=ErrorCode.EXECUTION_ERROR,
    )