Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(sfn): prefix aws-sdk error codes with service name for Catch matching (#296)
Jay Janssen47ec835df437
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c3902c28..826ab757 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ Versioning follows [Semantic Versioning](https://semver.org/).---+## [Unreleased]++### Fixed+- **SFN aws-sdk error code prefixing** — SDK errors from `aws-sdk:*` task integrations are now prefixed with the service name (e.g., `SecretsManager.ResourceExistsException` instead of bare `ResourceExistsException`), matching real AWS Step Functions behavior. This allows ASL `Catch` blocks that match on service-specific error codes (e.g., `SecretsManager.ResourceExistsException`) to work correctly. Contributed by @jayjanssen++---+## [1.2.9] — 2026-04-13### Addeddiff --git a/ministack/services/stepfunctions.py b/ministack/services/stepfunctions.pyindex e8b8106c..c25d78d9 100644--- a/ministack/services/stepfunctions.py+++ b/ministack/services/stepfunctions.py@@ -2189,6 +2189,47 @@ _AWS_SDK_SERVICE_MAP = {"lambda": {"protocol": "rest"},}+# Map lowercase service names used in aws-sdk ARNs to the PascalCase prefix+# that real AWS Step Functions uses when surfacing SDK errors (e.g.,+# "SecretsManager.ResourceExistsException").+_AWS_SDK_ERROR_PREFIX = {+ "secretsmanager": "SecretsManager",+ "dynamodb": "DynamoDb",+ "sfn": "Sfn",+ "logs": "CloudWatchLogs",+ "ssm": "Ssm",+ "eventbridge": "EventBridge",+ "kinesis": "Kinesis",+ "glue": "Glue",+ "athena": "Athena",+ "ecs": "Ecs",+ "ecr": "Ecr",+ "kms": "Kms",+ "sqs": "Sqs",+ "sns": "Sns",+ "rds": "Rds",+ "elasticache": "ElastiCache",+ "ec2": "Ec2",+ "iam": "Iam",+ "sts": "Sts",+ "cloudwatch": "CloudWatch",+ "rdsdata": "RdsData",+ "s3": "S3",+ "lambda": "Lambda",+}+++def _prefix_sdk_error(service_name: str, error_code: str) -> str:+ """Prefix an SDK error code with the service name, matching real AWS SFN behavior.++ E.g., ("secretsmanager", "ResourceExistsException") -> "SecretsManager.ResourceExistsException"+ If the error already has a dot prefix or is a States.* error, return as-is.+ """+ if "." in error_code:+ return error_code+ prefix = _AWS_SDK_ERROR_PREFIX.get(service_name, service_name.capitalize())+ return f"{prefix}.{error_code}"+# Static action→path maps for REST-JSON services.# Avoids a botocore runtime dependency for path resolution._REST_JSON_ACTION_PATHS = {@@ -2254,9 +2295,9 @@ def _dispatch_aws_sdk_json(service_info, service_name, action, input_data):result = json.loads(decoded) if decoded else {}if status >= 400:- error_type = result.get("__type", result.get("Error", {}).get("Code", f"{service_name}.ServiceException"))+ error_type = result.get("__type", result.get("Error", {}).get("Code", "ServiceException"))error_msg = result.get("message", result.get("Message", str(result)))- raise _ExecutionError(error_type, error_msg)+ raise _ExecutionError(_prefix_sdk_error(service_name, error_type), error_msg)# For JSON-protocol services, only convert top-level keys to avoid# mangling user-defined data (e.g. DynamoDB attribute names).@@ -2549,12 +2590,12 @@ def _dispatch_aws_sdk_query(service_info, service_name, action, input_data):msg = err_el.findtext("{http://rds.amazonaws.com/doc/2014-10-31/}Message")if msg is None:msg = err_el.findtext("Message")- raise _ExecutionError(code or f"{service_name}.ServiceException", msg or decoded)+ raise _ExecutionError(_prefix_sdk_error(service_name, code or "ServiceException"), msg or decoded)except _ExecutionError:raiseexcept Exception:pass- raise _ExecutionError(f"{service_name}.ServiceException", decoded)+ raise _ExecutionError(_prefix_sdk_error(service_name, "ServiceException"), decoded)# Convert successful XML response to dict, then apply SFN key naming conventiontry:@@ -2640,11 +2681,11 @@ def _dispatch_aws_sdk_rest_json(service_info, service_name, action, input_data):err_data = json.loads(decoded)code = err_data.get("code") or err_data.get("__type", "ServiceException")msg = err_data.get("message") or err_data.get("Message") or decoded- raise _ExecutionError(code, msg)+ raise _ExecutionError(_prefix_sdk_error(service_name, code), msg)except _ExecutionError:raiseexcept Exception:- raise _ExecutionError(f"{service_name}.ServiceException", decoded)+ raise _ExecutionError(_prefix_sdk_error(service_name, "ServiceException"), decoded)try:return json.loads(decoded) if decoded else {}diff --git a/tests/test_sfn.py b/tests/test_sfn.pyindex 77a7a1dc..2f7c6773 100644--- a/tests/test_sfn.py+++ b/tests/test_sfn.py@@ -2473,3 +2473,99 @@ def test_sfn_intrinsic_functions_batch_2(sfn, sfn_sync):assert output["add"] == 8assert len(output["uuid"]) == 36 # UUID formatsfn_sync.delete_state_machine(stateMachineArn=sm_arn)+++def test_sfn_aws_sdk_error_prefix_catch(sfn, sm):+ """aws-sdk errors are prefixed with the service name so Catch blocks match.++ Real AWS SFN surfaces SDK errors as "<ServiceName>.<ErrorCode>" (e.g.,+ "SecretsManager.ResourceExistsException"). Verify that a Catch block+ matching the prefixed form works correctly.+ """+ import uuid as _uuid++ secret_name = f"sdk-err-prefix-{_uuid.uuid4().hex[:8]}"++ # Pre-create the secret so the SFN's CreateSecret will fail.+ sm.create_secret(Name=secret_name, SecretString='{"test":"value"}')++ definition = json.dumps({+ "StartAt": "CreateDuplicate",+ "States": {+ "CreateDuplicate": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:secretsmanager:createSecret",+ "Parameters": {+ "Name": secret_name,+ "SecretString": '{"dup":"true"}',+ },+ "Catch": [+ {+ "ErrorEquals": ["SecretsManager.ResourceExistsException"],+ "ResultPath": "$.error",+ "Next": "Caught",+ }+ ],+ "End": True,+ },+ "Caught": {+ "Type": "Pass",+ "Result": "handled",+ "ResultPath": "$.recovered",+ "End": True,+ },+ },+ })++ sm_name = f"sdk-err-prefix-{_uuid.uuid4().hex[:8]}"+ sm_resp = sfn.create_state_machine(+ name=sm_name,+ definition=definition,+ roleArn="arn:aws:iam::000000000000:role/sfn-role",+ )++ ex = sfn.start_execution(stateMachineArn=sm_resp["stateMachineArn"], input="{}")+ desc = _wait_sfn(sfn, ex["executionArn"])++ assert desc["status"] == "SUCCEEDED", f"Expected SUCCEEDED, got {desc['status']}: {desc.get('cause', '')}"+ output = json.loads(desc["output"])+ assert output["recovered"] == "handled"+ assert "SecretsManager.ResourceExistsException" in output["error"]["Error"]++ # Cleanup.+ sfn.delete_state_machine(stateMachineArn=sm_resp["stateMachineArn"])+ sm.delete_secret(SecretId=secret_name, ForceDeleteWithoutRecovery=True)+++def test_sfn_aws_sdk_error_prefix_in_failed_execution(sfn, sfn_sync):+ """When no Catch matches, the prefixed error code appears in the execution failure."""+ import uuid as _uuid++ sm_name = f"sdk-err-nocatch-{_uuid.uuid4().hex[:8]}"++ definition = json.dumps({+ "StartAt": "DescribeMissing",+ "States": {+ "DescribeMissing": {+ "Type": "Task",+ "Resource": "arn:aws:states:::aws-sdk:rds:DescribeDBClusters",+ "Parameters": {+ "DBClusterIdentifier": "nonexistent-cluster-prefix-test",+ },+ "End": True,+ },+ },+ })++ sm_arn = sfn_sync.create_state_machine(+ name=sm_name,+ definition=definition,+ roleArn="arn:aws:iam::000000000000:role/sfn-role",+ )["stateMachineArn"]++ resp = sfn_sync.start_sync_execution(stateMachineArn=sm_arn, input="{}")+ assert resp["status"] == "FAILED"+ # Error should have the "Rds." prefix.+ assert resp.get("error", "").startswith("Rds."), f"Expected Rds. prefix, got: {resp.get('error', '')}"++ sfn_sync.delete_state_machine(stateMachineArn=sm_arn)