Profiles·Public

@aws-sdk/client-secrets-manager

semver>=3.0.0 <4.0.0postconditions48functions19last verified2026-06-24coverage score79%

Postconditions: what we check

  • send · aws-secrets-manager-service-error
    error
    WhenAny AWS service error or network failure: secret does not exist (ResourceNotFoundException), secret already exists when creating (ResourceExistsException), invalid request state (InvalidRequestException), invalid parameter (InvalidParameterException), permission denied (AccessDeniedException), KMS errors (DecryptionFailure, EncryptionFailure), request throttling (ThrottlingException), service unavailable, or any network-level failure (DNS, timeout, connection refused)
    ThrowsSecretsManagerServiceException subclass with error.name set to the specific error code (e.g., "ResourceNotFoundException", "ResourceExistsException", "InvalidRequestException", "AccessDeniedException", "ThrottlingException"). For network errors, throws a generic Error or SdkClientError with a connection/timeout message.
    Required handlingCaller MUST wrap client.send() in try-catch. All Secrets Manager operations can fail due to network issues, permission problems, missing secrets, or AWS service outages. Unhandled rejections on GetSecretValueCommand cause application crashes when secrets are unavailable; unhandled CreateSecretCommand/UpdateSecretCommand failures cause silent data loss. Minimum handling: try { const response = await smClient.send(new GetSecretValueCommand({ SecretId: 'my/secret' })); return response.SecretString; } catch (error) { if (error instanceof SecretsManagerServiceException) { console.error(`Secrets Manager error [${error.name}]: ${error.message}`); } else { console.error('Network error:', error); } throw error; } For ResourceNotFoundException: consider whether the missing secret represents a configuration error (throw) or a valid absent state (return null/default).
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
  • GetSecretValueCommand · get-secret-value-not-found
    error
    Whensecret does not exist, the ARN references a deleted secret, or the secret was created in a different region; throws ResourceNotFoundException (error.name === "ResourceNotFoundException")
    ThrowsResourceNotFoundException
    Required handlingCatch ResourceNotFoundException and handle missing secret explicitly. Check that the secret name matches the environment (dev/staging/prod). Either throw with a descriptive message or return a default value if the missing secret represents an optional feature.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • GetSecretValueCommand · get-secret-value-decryption-failure
    error
    WhenKMS key used to encrypt the secret is unavailable, disabled, deleted, or the caller lacks kms:Decrypt permission; throws DecryptionFailure (error.name === "DecryptionFailure")
    ThrowsDecryptionFailure
    Required handlingCatch DecryptionFailure and log the KMS key ARN and error details. Alert the on-call team — this indicates a KMS permission or key lifecycle issue that requires manual remediation. Do not retry without fixing the underlying KMS configuration.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • GetSecretValueCommand · get-secret-value-no-try-catch
    error
    Whencaller invokes await smClient.send(new GetSecretValueCommand(...)) without a wrapping try-catch
    ThrowsResourceNotFoundException, DecryptionFailure, AccessDeniedException, or network errors propagate as unhandled rejections
    Required handlingAlways wrap in try-catch: try { const result = await smClient.send(new GetSecretValueCommand({ SecretId: secretName, VersionStage: 'AWSCURRENT' })); const secret = result.SecretString ?? Buffer.from(result.SecretBinary).toString('utf8'); return JSON.parse(secret); } catch (error) { if (error instanceof ResourceNotFoundException) { throw new Error(`Secret '${secretName}' not found — check region and name`); } throw error; } Note: always check both SecretString and SecretBinary — only one is populated.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilitycatastrophic
    Sources[2][1]
  • BatchGetSecretValueCommand · batch-get-secret-partial-failure-unchecked
    error
    WhenBatchGetSecretValueCommand returns HTTP 200 (Promise resolves) even when individual secrets fail; per-secret errors appear in response.Errors[] but caller does not check response.Errors after the call
    Required handlingAlways check response.Errors after the call: const response = await smClient.send(new BatchGetSecretValueCommand({ SecretIdList: ['db/prod', 'api/stripe', 'jwt/signing-key'] })); if (response.Errors && response.Errors.length > 0) { const failures = response.Errors.map(e => `${e.SecretId}: ${e.ErrorCode} — ${e.Message}` ).join('\n'); throw new Error(`BatchGetSecretValue partial failure:\n${failures}`); } return response.SecretValues;
    costhighin prodsilent failureusers seelost datavisibilitysilent
    Sources[5]
  • BatchGetSecretValueCommand · batch-get-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new BatchGetSecretValueCommand(...)) without a wrapping try-catch; request-level errors (DecryptionFailure for KMS, InvalidNextTokenException, InternalServiceError, network failures) still throw
    ThrowsRequest-level errors including DecryptionFailure, InvalidNextTokenException, InternalServiceError, and network failures
    Required handlingWrap the entire call in try-catch to handle request-level failures. Also check response.Errors[] for per-secret failures after the call succeeds. Both error channels must be handled independently.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilitycatastrophic
    Sources[5]
  • CreateSecretCommand · create-secret-already-exists
    error
    Whena secret with the requested Name already exists in the account and region; throws ResourceExistsException (error.name === "ResourceExistsException")
    ThrowsResourceExistsException
    Required handlingHandle ResourceExistsException explicitly: try { await smClient.send(new CreateSecretCommand({ Name, SecretString })); } catch (error) { if (error instanceof ResourceExistsException) { // Secret already exists — update instead await smClient.send(new UpdateSecretCommand({ SecretId: Name, SecretString })); } else { throw error; } }
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[6]
  • CreateSecretCommand · create-secret-kms-encryption-failure
    error
    Whenspecified KMS key cannot be used to encrypt the secret value — key is disabled, deleted, pending deletion, or caller lacks kms:GenerateDataKey and kms:Decrypt permissions; throws EncryptionFailure (error.name === "EncryptionFailure")
    ThrowsEncryptionFailure
    Required handlingCatch EncryptionFailure and verify KMS key status and IAM permissions. Log the KMS key ARN and the error. Do not assume the secret was created. Alert the on-call team — this requires KMS configuration remediation.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[6]
  • CreateSecretCommand · create-secret-limit-exceeded
    warning
    Whenrequest would exceed account-level Secrets Manager quota (default 500,000 secrets per account per region) or Tags quota (max 50 tags per secret); throws LimitExceededException (error.name === "LimitExceededException")
    ThrowsLimitExceededException
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[6][7]
  • CreateSecretCommand · create-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new CreateSecretCommand(...)) without a wrapping try-catch
    ThrowsResourceExistsException, EncryptionFailure, LimitExceededException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. At minimum handle ResourceExistsException to enable idempotent provisioning (catch and update instead of failing). Log all other errors and re-throw to prevent silent provisioning failures.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilitycatastrophic
    Sources[6]
  • PutSecretValueCommand · put-secret-value-secret-not-found
    error
    Whenspecified SecretId does not exist; PutSecretValueCommand requires the secret to already exist unlike CreateSecretCommand; throws ResourceNotFoundException (error.name === "ResourceNotFoundException")
    ThrowsResourceNotFoundException
    Required handlingCatch ResourceNotFoundException and verify the SecretId. Either create the secret first with CreateSecretCommand, or check whether the secret name differs between environments (dev/staging/prod).
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[8]
  • PutSecretValueCommand · put-secret-value-version-conflict
    error
    WhenClientRequestToken matches an existing version ID but SecretString or SecretBinary values differ from the existing version; throws ResourceExistsException (error.name === "ResourceExistsException")
    ThrowsResourceExistsException
    Required handlingCatch ResourceExistsException and use a unique ClientRequestToken (e.g., UUID) on each rotation attempt, or omit ClientRequestToken to let the SDK generate one. Do not reuse deterministic token IDs across calls with different secret values.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[8]
  • PutSecretValueCommand · put-secret-value-throttling
    warning
    WhenPutSecretValue is called more than approximately once per 10 minutes for the same secret, exceeding the version quota; throws LimitExceededException (error.name === "LimitExceededException")
    ThrowsLimitExceededException
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[8][7]
  • PutSecretValueCommand · put-secret-value-no-try-catch
    error
    Whencaller invokes await smClient.send(new PutSecretValueCommand(...)) without a wrapping try-catch
    ThrowsResourceNotFoundException, ResourceExistsException, EncryptionFailure, LimitExceededException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Handle ResourceNotFoundException (secret missing) and LimitExceededException (version quota). Log all errors and do not assume the rotation succeeded on failure — keep using the old credential until rotation is confirmed.
    costhighin prodsilent failureusers seelost datavisibilitysilent
    Sources[8]
  • UpdateSecretCommand · update-secret-not-found
    error
    Whenspecified SecretId does not exist; UpdateSecret cannot create a new secret; throws ResourceNotFoundException (error.name === "ResourceNotFoundException")
    ThrowsResourceNotFoundException
    Required handlingCatch ResourceNotFoundException and verify the secret exists before updating. Either create the secret first with CreateSecretCommand or validate the SecretId is correct for the target environment.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[9]
  • UpdateSecretCommand · update-secret-kms-errors
    error
    Whenexisting secret cannot be decrypted with the current KMS key (DecryptionFailure), or new value cannot be encrypted with specified KMS key (EncryptionFailure); common when rotating KMS keys or migrating to customer-managed keys
    ThrowsDecryptionFailure or EncryptionFailure
    Required handlingCatch DecryptionFailure and EncryptionFailure separately. Log the KMS key ARN and alert the on-call team — KMS errors require manual key configuration remediation and cannot be resolved by retrying.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[9]
  • UpdateSecretCommand · update-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new UpdateSecretCommand(...)) without a wrapping try-catch
    ThrowsResourceNotFoundException, DecryptionFailure, EncryptionFailure, LimitExceededException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Handle ResourceNotFoundException for missing secrets and KMS errors for encryption failures. Log failures and do not assume the update succeeded — stale secret values may remain in use silently.
    costhighin prodsilent failureusers seelost datavisibilitysilent
    Sources[9]
  • DeleteSecretCommand · delete-secret-recovery-window-not-immediate
    warning
    WhenDeleteSecretCommand with RecoveryWindowInDays (default 30 days) does NOT immediately destroy the secret; the secret name cannot be reused until the window expires; GetSecretValueCommand on a scheduled-deletion secret throws InvalidRequestException, not ResourceNotFoundException
    Required handlingUse RecoveryWindowInDays: 7 for the minimum window, or ForceDeleteWithoutRecovery: true for immediate permanent deletion. If creating a replacement secret immediately after deletion, use a different name or wait for the recovery window to expire.
    costmediumin proddelayed failureusers seeservice unavailablevisibilityvisible
    Sources[10]
  • DeleteSecretCommand · delete-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new DeleteSecretCommand(...)) without a wrapping try-catch; ResourceNotFoundException (for normal delete of non-existent secret), InvalidRequestException, and network errors propagate; note: ForceDeleteWithoutRecovery on a non-existent secret does NOT throw
    ThrowsResourceNotFoundException, InvalidRequestException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Handle ResourceNotFoundException to make delete idempotent (catch and continue if secret doesn't exist). Handle InvalidRequestException for secrets managed by other services. Log all other errors.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[10]
  • RotateSecretCommand · rotate-secret-async-completion-assumed
    warning
    WhenRotateSecretCommand resolves immediately with the new VersionId, but the rotation Lambda function runs asynchronously; code reads the secret immediately after RotateSecretCommand returns and may read the old AWSCURRENT value or an intermediate AWSPENDING value
    Required handlingAfter calling RotateSecretCommand, poll DescribeSecretCommand until response.RotationEnabled === true and response.LastRotatedDate is updated, or implement a wait before reading the new value: const rotateResult = await smClient.send(new RotateSecretCommand({ SecretId: secretName, RotateImmediately: true })); // Do NOT immediately read the secret — wait for Lambda to complete // Poll DescribeSecret until LastRotatedDate changes, or use SQS notification
    costmediumin proddelayed failureusers seeservice unavailablevisibilityvisible
    Sources[11]
  • RotateSecretCommand · rotate-secret-lambda-not-configured
    error
    WhenRotateImmediately is true but no RotationLambdaARN is provided and no rotation Lambda has been previously configured, or the Lambda function ARN is invalid or deleted; throws InvalidRequestException (error.name === "InvalidRequestException")
    ThrowsInvalidRequestException
    Required handlingCatch InvalidRequestException and check that a rotation Lambda function is configured for the secret before calling RotateSecretCommand. Set up the Lambda ARN via RotationLambdaARN parameter or via the AWS console first.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[11]
  • RotateSecretCommand · rotate-secret-in-progress
    warning
    Whena previous rotation is still in progress (AWSPENDING label is present but not yet attached to AWSCURRENT); calling RotateSecret again while rotation is in progress always throws InvalidRequestException (error.name === "InvalidRequestException")
    ThrowsInvalidRequestException
    costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[11]
  • RotateSecretCommand · rotate-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new RotateSecretCommand(...)) without a wrapping try-catch
    ThrowsInvalidRequestException (Lambda not configured, rotation in progress), ResourceNotFoundException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Handle InvalidRequestException to detect rotation-in-progress vs Lambda-not-configured cases (check error.message). Log all errors — a failed rotation call means credentials were NOT rotated despite the caller expecting the rotation to have started.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilitycatastrophic
    Sources[11]
  • UpdateSecretVersionStageCommand · update-secret-version-stage-limit-exceeded
    error
    Whentotal staging labels attached across all versions of the secret reaches the hard limit of 20; each custom label added without removing old ones exhausts the quota; throws LimitExceededException (error.name === "LimitExceededException")
    ThrowsLimitExceededException
    Required handlingBefore adding a new staging label, check existing labels via ListSecretVersionIds. Clean up obsolete custom labels to stay under the limit of 20 labels across all versions. Rotation Lambdas that accumulate custom labels per deployment will hit this limit after 20 deployments if labels are never removed.
    costmediumin prodimmediate exceptionusers seedegraded performancevisibilityvisible
    Sources[12][7]
  • UpdateSecretVersionStageCommand · update-secret-version-stage-invalid-request
    error
    Whenthe secret is scheduled for deletion, the label being moved is AWSCURRENT but RemoveFromVersionId is missing or mismatched, the secret is managed by another AWS service (e.g., RDS managed rotation), or the label is already the only label on a version (removing it would deprecate the version unexpectedly); throws InvalidRequestException (error.name === "InvalidRequestException")
    ThrowsInvalidRequestException
    Required handlingHandle InvalidRequestException to detect state conflicts. When using UpdateSecretVersionStage to promote AWSCURRENT during rotation, always provide both MoveToVersionId and RemoveFromVersionId to avoid ambiguous state transitions. Check error.message for details on which constraint was violated.
    costmediumin prodimmediate exceptionusers seedegraded performancevisibilityvisible
    Sources[12]
  • UpdateSecretVersionStageCommand · update-secret-version-stage-no-try-catch
    error
    Whencaller invokes await smClient.send(new UpdateSecretVersionStageCommand(...)) without a wrapping try-catch
    ThrowsLimitExceededException, InvalidRequestException, ResourceNotFoundException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Failed UpdateSecretVersionStage in a rotation Lambda means the new secret version was never promoted to AWSCURRENT — the old (possibly expired/rotated) credentials remain active while the application believes rotation completed. This is a silent security incident.
    costhighin prodimmediate exceptionusers seedegraded performancevisibilitycatastrophic
    Sources[12]
  • CancelRotateSecretCommand · cancel-rotate-secret-orphaned-pending-version
    warning
    Whenrotation is cancelled mid-flight (AWSPENDING label attached to an incomplete version); the response.VersionId field is populated with the incomplete version that must be cleaned up; leaving it uncleaned can block future rotations from starting (no-try-catch means the caller never sees response.VersionId)
    Throwsdoes not throw — response.VersionId contains the orphaned version ID; the risk is NOT handling the returned VersionId
    Required handlingAfter calling CancelRotateSecretCommand, always check response.VersionId. If present, call UpdateSecretVersionStage to remove the AWSPENDING label from that version. Failing to clean up leaves a partial version that blocks re-enabling rotation. Example cleanup: const result = await smClient.send(new CancelRotateSecretCommand({ SecretId: 'my/secret' })); if (result.VersionId) { await smClient.send(new UpdateSecretVersionStageCommand({ SecretId: 'my/secret', VersionStage: 'AWSPENDING', RemoveFromVersionId: result.VersionId, })); }
    costmediumin prodsilent failureusers seedegraded performancevisibilitysilent
    Sources[13]
  • CancelRotateSecretCommand · cancel-rotate-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new CancelRotateSecretCommand(...)) without a wrapping try-catch
    ThrowsInvalidRequestException (secret is managed by another service), ResourceNotFoundException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Incident response scripts that call CancelRotateSecret must handle errors — if the cancel fails, rotation continues running and the incident response action had no effect.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[13]
  • PutResourcePolicyCommand · put-resource-policy-public-policy-exception
    error
    WhenBlockPublicPolicy is true and the provided policy grants overly broad access (e.g., principal is "*" or uses wildcards that AWS evaluates as public access); throws PublicPolicyException (error.name === "PublicPolicyException")
    ThrowsPublicPolicyException
    Required handlingCatch PublicPolicyException and reject the policy. This exception is the guard that prevents accidental secret exposure. Never suppress it silently — it means the policy as written would expose the secret to the public. Always set BlockPublicPolicy: true in production environments.
    costcriticalin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[14]
  • PutResourcePolicyCommand · put-resource-policy-malformed-policy
    error
    Whenthe ResourcePolicy JSON string has syntax errors or references invalid AWS principals/actions; throws MalformedPolicyDocumentException (error.name === "MalformedPolicyDocumentException")
    ThrowsMalformedPolicyDocumentException
    Required handlingValidate IAM policy JSON before calling PutResourcePolicy. Catch MalformedPolicyDocumentException and log error.message which contains AWS policy parser details about the specific syntax issue. Use ValidateResourcePolicyCommand to pre-validate before applying.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[14]
  • PutResourcePolicyCommand · put-resource-policy-no-try-catch
    error
    Whencaller invokes await smClient.send(new PutResourcePolicyCommand(...)) without a wrapping try-catch
    ThrowsPublicPolicyException, MalformedPolicyDocumentException, InvalidRequestException, ResourceNotFoundException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. A failed PutResourcePolicy in cross-account setup scripts means the intended principal cannot access the secret — silent failure causes access denials that are difficult to diagnose.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[14]
  • RestoreSecretCommand · restore-secret-invalid-request
    error
    Whenthe secret is NOT scheduled for deletion (RestoreSecret is called on an active, non-deleted secret) or the secret was force-deleted with ForceDeleteWithoutRecovery (no recovery window exists); throws InvalidRequestException (error.name === "InvalidRequestException")
    ThrowsInvalidRequestException
    Required handlingBefore calling RestoreSecret, verify the secret is in a deleted state by calling DescribeSecretCommand and checking response.DeletedDate. Catch InvalidRequestException and check error.message to distinguish "not in deleted state" from "force-deleted with no recovery window". Force-deleted secrets are permanently gone and cannot be restored.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[15]
  • RestoreSecretCommand · restore-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new RestoreSecretCommand(...)) without a wrapping try-catch
    ThrowsInvalidRequestException (not in deleted state or force-deleted), ResourceNotFoundException (secret name not found), and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Disaster recovery scripts that call RestoreSecret must handle errors — an unhandled rejection means the script silently failed and the secret remains inaccessible.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[15]
  • DescribeSecretCommand · describe-secret-not-found
    error
    Whenspecified SecretId does not exist, the ARN references a deleted secret, or the secret was created in a different region; throws ResourceNotFoundException (error.name === "ResourceNotFoundException")
    ThrowsResourceNotFoundException
    Required handlingCatch ResourceNotFoundException explicitly. DescribeSecret is often called from monitoring code paths where a missing secret should be alerted rather than silently swallowed. Either return null/default for optional secrets or throw a descriptive error naming the environment and region.
    costmediumin prodimmediate exceptionusers seedegraded performancevisibilityvisible
    Sources[16]
  • DescribeSecretCommand · describe-secret-rotation-status-stale-read
    warning
    Whencaller invokes DescribeSecretCommand inside a polling loop (e.g. waiting for RotateSecretCommand to complete) but reads response.LastRotatedDate or response.NextRotationDate without checking that the rotation Lambda actually completed (response.RotationEnabled === true AND response.LastRotatedDate is recent); stale rotation status produces false "rotation succeeded" signals
    Required handlingWhen polling DescribeSecret for rotation completion: const before = await smClient.send(new DescribeSecretCommand({ SecretId })); await smClient.send(new RotateSecretCommand({ SecretId, RotateImmediately: true })); // Poll until LastRotatedDate moves forward let attempts = 0; while (attempts++ < MAX_ATTEMPTS) { await sleep(POLL_INTERVAL_MS); const status = await smClient.send(new DescribeSecretCommand({ SecretId })); if (status.LastRotatedDate && (!before.LastRotatedDate || status.LastRotatedDate > before.LastRotatedDate)) { return; // rotation completed } } throw new Error('Rotation polling timed out — Lambda may have failed');
    costmediumin prodsilent failureusers seelost datavisibilitysilent
    Sources[16][17]
  • DescribeSecretCommand · describe-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new DescribeSecretCommand(...)) without a wrapping try-catch
    ThrowsResourceNotFoundException, InvalidParameterException, InternalServiceError, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. DescribeSecret is often called from health-check endpoints and rotation status pollers — unhandled rejections crash monitoring jobs and falsely signal that rotation is broken. Distinguish ResourceNotFoundException (alert: secret missing) from InternalServiceError (alert: AWS issue, retry with backoff).
    costmediumin prodimmediate exceptionusers seedegraded performancevisibilityvisible
    Sources[16]
  • ReplicateSecretToRegionsCommand · replicate-secret-per-region-failure-unchecked
    error
    WhenReplicateSecretToRegionsCommand returns HTTP 200 (Promise resolves) even when individual region replications fail; per-region errors appear in response.ReplicationStatus[] with Status === "Failed" but the caller does not iterate response.ReplicationStatus to check each region's status
    Required handlingAlways check response.ReplicationStatus after the call: const result = await smClient.send(new ReplicateSecretToRegionsCommand({ SecretId: SECRET_ID, AddReplicaRegions: [{ Region: 'us-west-2' }, { Region: 'eu-west-1' }] })); const failures = (result.ReplicationStatus ?? []).filter( s => s.Status === 'Failed' ); if (failures.length > 0) { const detail = failures .map(f => `${f.Region}: ${f.StatusMessage ?? 'unknown'}`) .join('\n'); throw new Error(`Replication failed in regions:\n${detail}`); } // Also track InProgress — replication is async per region const pending = (result.ReplicationStatus ?? []).filter( s => s.Status === 'InProgress' ); return { replicated: result.ReplicationStatus, pending };
    costhighin prodsilent failureusers seelost datavisibilitysilent
    Sources[18]
  • ReplicateSecretToRegionsCommand · replicate-secret-async-completion-assumed
    warning
    WhenReplicateSecretToRegionsCommand resolves with Status === "InProgress" for some regions; caller assumes replication completed and immediately uses the replica in another region, before AWS has finished provisioning
    Required handlingAfter calling ReplicateSecretToRegionsCommand, do NOT assume the secret is immediately available in the target region. Poll DescribeSecretCommand (with the region client switched to the replica region) and check ReplicationStatus until Status === "InSync" before depending on the replica. Document a wait window in disaster-recovery runbooks.
    costmediumin proddelayed failureusers seedegraded performancevisibilitysilent
    Sources[18][19]
  • ReplicateSecretToRegionsCommand · replicate-secret-no-try-catch
    error
    Whencaller invokes await smClient.send(new ReplicateSecretToRegionsCommand(...)) without a wrapping try-catch; request-level errors (the secret itself does not exist, invalid parameters, internal service errors, KMS permission failures in the target region) still throw, distinct from per-region Failed entries
    ThrowsResourceNotFoundException, InvalidParameterException, InvalidRequestException, InternalServiceError, and network errors propagate as unhandled rejections
    Required handlingWrap the entire call in try-catch to handle request-level failures. ALSO iterate response.ReplicationStatus to detect per-region Failed entries. Both error channels must be handled independently — a failed try-catch means no replication started; a Failed entry means one specific region's replica is broken while others may have succeeded.
    costhighin prodsilent failureusers seelost datavisibilitycatastrophic
    Sources[18]
  • ValidateResourcePolicyCommand · validate-resource-policy-passed-flag-unchecked
    error
    WhenValidateResourcePolicyCommand returns HTTP 200 (Promise resolves) with response.PolicyValidationPassed === false when the policy fails AWS-side validation, but the caller does not check PolicyValidationPassed before proceeding to call PutResourcePolicyCommand with the same policy; a broken policy is attached and the validation pre-flight is rendered useless
    Required handlingAlways check response.PolicyValidationPassed before applying the policy: const validation = await smClient.send(new ValidateResourcePolicyCommand({ SecretId: SECRET_ID, ResourcePolicy: policyJson, })); if (!validation.PolicyValidationPassed) { const detail = (validation.ValidationErrors ?? []) .map(e => `[${e.CheckName}] ${e.ErrorMessage}`) .join('\n'); throw new Error(`Resource policy invalid:\n${detail}`); } // Only NOW apply the policy await smClient.send(new PutResourcePolicyCommand({ SecretId: SECRET_ID, ResourcePolicy: policyJson, BlockPublicPolicy: true, }));
    costhighin prodsilent failureusers seedegraded performancevisibilitysilent
    Sources[20]
  • ValidateResourcePolicyCommand · validate-resource-policy-no-try-catch
    error
    Whencaller invokes await smClient.send(new ValidateResourcePolicyCommand(...)) without a wrapping try-catch; request-level errors throw distinct from the PolicyValidationPassed === false silent-failure path
    ThrowsMalformedPolicyDocumentException (JSON syntax error in the policy), ResourceNotFoundException (secret name not found), InvalidParameterException, InternalServiceError, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Catch MalformedPolicyDocumentException specifically — this means the policy JSON itself is unparseable, distinct from PolicyValidationPassed === false (parseable but semantically wrong). Both must be handled to make policy validation reliable.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[20]
  • TagResourceCommand · tag-resource-limit-exceeded
    warning
    Whentotal tags attached to the secret would exceed the per-secret limit of 50 tags; throws LimitExceededException (error.name === "LimitExceededException")
    ThrowsLimitExceededException
    Required handlingBefore adding tags, count existing tags via DescribeSecretCommand and response.Tags.length. Either remove obsolete tags via UntagResourceCommand or batch the tagging operation. Compliance scripts that blindly add a tag-per-deployment will hit this limit after 50 deployments.
    costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisible
    Sources[21][7]
  • TagResourceCommand · tag-resource-no-try-catch
    error
    Whencaller invokes await smClient.send(new TagResourceCommand(...)) without a wrapping try-catch
    ThrowsResourceNotFoundException, LimitExceededException, InvalidParameterException, InvalidRequestException, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. CI/CD tagging pipelines that fail silently produce cost allocation reports missing entire categories of secrets and break IAM policies that use tag conditions for access control. Treat tagging failures as deployment failures, not silent warnings.
    costlowin prodimmediate exceptionusers seedegraded performancevisibilitysilent
    Sources[21]
  • GetRandomPasswordCommand · get-random-password-no-try-catch
    error
    Whencaller invokes await smClient.send(new GetRandomPasswordCommand(...)) without a wrapping try-catch; failures here in rotation Lambdas mean rotation stalls AND CloudWatch sees an uncaught exception in the Lambda, marking rotation as failed without rolling back any partial state
    ThrowsInvalidParameterException (invalid PasswordLength, conflicting IncludeSpace/ExcludeCharacters), InvalidRequestException, InternalServiceError, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Inside a rotation Lambda, a GetRandomPassword failure must be caught and re-thrown with rotation-specific context so the AWSPENDING label is never created with a missing or partial value. Outside rotation, log the failure and never fall back to a weak deterministic password.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[22]
  • UntagResourceCommand · untag-resource-self-lockout
    warning
    Whencaller removes a tag whose key appears in an IAM policy condition that grants the caller access to the secret; the operation is blocked and AWS returns AccessDeniedException; subsequent calls on the same secret from the same principal will also fail
    ThrowsAccessDeniedException (error.name === "AccessDeniedException") when the tag removal would strip the calling principal's own access; the secret remains tagged but the caller can no longer act on it
    Required handlingBefore calling UntagResourceCommand in automated compliance scripts, enumerate the IAM policies governing the secret (or maintain a list of tag keys that participate in access control) and refuse to remove tags whose keys appear in those conditions. Catch AccessDeniedException explicitly and surface it as a configuration error, NOT a generic retry-able failure — retrying will fail identically and add noise.
    costmediumin prodimmediate exceptionusers seeauthentication failurevisibilityvisible
    Sources[23][24]
  • UntagResourceCommand · untag-resource-no-try-catch
    error
    Whencaller invokes await smClient.send(new UntagResourceCommand(...)) without a wrapping try-catch; while missing tags are idempotent, the operation still throws on ResourceNotFoundException (wrong secret ARN), InvalidRequestException (secret scheduled for deletion or managed by another service), and AccessDeniedException (self-lockout via tag-based IAM condition); network errors also propagate
    ThrowsResourceNotFoundException, InvalidRequestException, AccessDeniedException, InvalidParameterException, InternalServiceError, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Compliance scripts that strip stale tags from hundreds of secrets must surface per-secret failures; an unhandled rejection in a batch tag-cleanup job leaves the secret partially re-tagged and the report partially populated, which is worse than a clean failure because the operator believes the cleanup succeeded.
    costlowin prodimmediate exceptionusers seedegraded performancevisibilitysilent
    Sources[23]
  • StopReplicationToReplicaCommand · stop-replication-wrong-region-invocation
    error
    Whencaller invokes StopReplicationToReplicaCommand from the primary Region's client (not the replica Region's client); AWS rejects the call with InvalidRequestException because the operation only succeeds when issued against the replica's own regional endpoint
    ThrowsInvalidRequestException (error.name === "InvalidRequestException") with a message indicating the operation must be invoked from the replica's Region; the topology is unchanged but disaster-recovery automation believes promotion has begun
    Required handlingAlways construct a NEW SecretsManagerClient pinned to the replica Region for this call (e.g. `new SecretsManagerClient({ region: replicaRegion })`) — do NOT reuse the primary-region client. Catch InvalidRequestException and verify the client's resolved region matches the intended replica before retrying. Treat this as a programming error, not a transient failure; retrying with the same client will fail identically.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[25]
  • StopReplicationToReplicaCommand · stop-replication-no-try-catch
    error
    Whencaller invokes await smClient.send(new StopReplicationToReplicaCommand(...)) without a wrapping try-catch; this is an IRREVERSIBLE promotion of the replica to a primary — any unhandled rejection in disaster-recovery automation aborts the failover with no rollback path, leaving the original primary still authoritative while operators believe failover has begun
    ThrowsInvalidRequestException (wrong-region call, secret managed by another service, secret scheduled for deletion), ResourceNotFoundException, InvalidParameterException, InternalServiceError, and network errors propagate as unhandled rejections
    Required handlingWrap in try-catch. Disaster recovery runbooks MUST log the exact error before retrying and MUST NOT proceed to dependent steps (e.g. updating Route53 to point at the new primary Region) until the promotion is confirmed via DescribeSecretCommand showing ReplicationStatus is empty / PrimaryRegion is the replica's region. Treat StopReplicationToReplica failure as a STOP-THE-LINE event in failover automation — silent retries can produce split-brain topologies where two regions both believe they own the secret.
    costhighin prodimmediate exceptionusers seelost datavisibilitysilent
    Sources[25]

Sources

Every postcondition cites at least one of these. Grouped by source type; numbered to match the footnotes above.

Official documentation

Research notes

Curator notes from SOURCES.md captured when the profile was written so you can verify the reasoning, not just the rules.

Sources — @aws-sdk/client-secrets-manager

Primary Documentation

Error Hierarchy

SecretsManagerServiceException is the base class for all service errors. Thrown from client.send() for any service-level failure.

Common Error Codes (error.name)

ErrorCause
ResourceNotFoundExceptionSecret does not exist or was deleted
ResourceExistsExceptionCreating a secret that already exists
InvalidRequestExceptionOperation not valid in current state (e.g., already scheduled for deletion)
InvalidParameterExceptionMalformed request parameter
AccessDeniedExceptionIAM permissions insufficient
DecryptionFailureKMS key cannot decrypt the secret
EncryptionFailureKMS key cannot encrypt the secret
ThrottlingExceptionRequest rate exceeds limit — retryable
InternalServiceErrorAWS-side error — retryable

Why error handling is required

  1. GetSecretValueCommand: If the secret does not exist or IAM permissions are missing, the application crashes at startup or returns uninitialized credentials — silently or with an uncaught rejection.

  2. CreateSecretCommand / UpdateSecretCommand: If the operation fails, secrets are not persisted. Applications may continue operating with stale or missing credentials.

  3. RotateSecretCommand: Rotation happens asynchronously. Without error handling, failed rotation attempts are silently ignored.

Evidence

  • Real-world TPs found in n8n (testing/containers/services/localstack.ts): createSecret() and getSecret() call client.send() without try-catch
  • Wing SDK platform.ts wraps all Secrets Manager calls in try-catch (correct usage)
Need a different package?
Request a profile