Skip to content

Commit b6b91dd

Browse files
authored
feat(codedeploy): throw ValidationErrors instead of untyped Errors (#33853)
### Issue # (if applicable) Relates to #32569 ### Reason for this change untyped Errors are not recommended ### Description of changes ValidationErrors everywhere ### Describe any new or updated permissions being added None ### Description of how you validated changes Existing tests. Exemptions granted as this is a refactor of existing code. ### Checklist - [x] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md) ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
1 parent 38d82c4 commit b6b91dd

File tree

8 files changed

+31
-31
lines changed

8 files changed

+31
-31
lines changed

packages/aws-cdk-lib/.eslintrc.js

+4-2
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,15 @@ const enableNoThrowDefaultErrorIn = [
3434
'aws-batch',
3535
'aws-chatbot',
3636
'aws-certificatemanager',
37-
'aws-codebuild',
38-
'aws-cognito',
3937
'aws-cloudfront',
4038
'aws-cloudfront-origins',
4139
'aws-cloudtrail',
4240
'aws-cloudwatch',
4341
'aws-cloudwatch-actions',
42+
'aws-codeartifact',
43+
'aws-codebuild',
44+
'aws-cognito',
45+
'aws-codedeploy',
4446
'aws-ecr',
4547
'aws-elasticloadbalancing',
4648
'aws-elasticloadbalancingv2',

packages/aws-cdk-lib/aws-codedeploy/lib/base-deployment-config.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { CfnDeploymentConfig } from './codedeploy.generated';
33
import { MinimumHealthyHosts, MinimumHealthyHostsPerZone } from './host-health-config';
44
import { arnForDeploymentConfig, validateName } from './private/utils';
55
import { TrafficRouting } from './traffic-routing-config';
6-
import { ArnFormat, Duration, Resource, Stack } from '../../core';
6+
import { ArnFormat, Duration, Resource, Stack, ValidationError } from '../../core';
77

88
/**
99
* The base class for ServerDeploymentConfig, EcsDeploymentConfig,
@@ -174,12 +174,12 @@ export abstract class BaseDeploymentConfig extends Resource implements IBaseDepl
174174

175175
// Traffic routing is not applicable to Server-based deployment configs
176176
if (props?.trafficRouting && (props?.computePlatform === undefined || props?.computePlatform === ComputePlatform.SERVER)) {
177-
throw new Error('Traffic routing config must not be specified for a Server-base deployment configuration');
177+
throw new ValidationError('Traffic routing config must not be specified for a Server-base deployment configuration', this);
178178
}
179179

180180
// Minimum healthy hosts is only applicable to Server-based deployment configs
181181
if (props?.minimumHealthyHosts && props?.computePlatform && props?.computePlatform !== ComputePlatform.SERVER) {
182-
throw new Error('Minimum healthy hosts config must only be specified for a Server-base deployment configuration');
182+
throw new ValidationError('Minimum healthy hosts config must only be specified for a Server-base deployment configuration', this);
183183
}
184184

185185
if (props?.zonalConfig) {
@@ -217,7 +217,7 @@ export abstract class BaseDeploymentConfig extends Resource implements IBaseDepl
217217
private validateMinimumDuration(duration: Duration, name: string) {
218218
const milliseconds = duration.toMilliseconds();
219219
if (milliseconds > 0 && milliseconds < 1000) {
220-
throw new Error(`${name} must be greater than or equal to 1 second or be equal to 0, got ${milliseconds}ms`);
220+
throw new ValidationError(`${name} must be greater than or equal to 1 second or be equal to 0, got ${milliseconds}ms`, this);
221221
}
222222
}
223223
}

packages/aws-cdk-lib/aws-codedeploy/lib/ecs/deployment-group.ts

+4-7
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import * as ecs from '../../../aws-ecs';
66
import * as elbv2 from '../../../aws-elasticloadbalancingv2';
77
import * as iam from '../../../aws-iam';
88
import * as cdk from '../../../core';
9+
import { ValidationError } from '../../../core';
910
import { addConstructMetadata, MethodMetadata } from '../../../core/lib/metadata-resource';
1011
import { CODEDEPLOY_REMOVE_ALARMS_FROM_DEPLOYMENT_GROUP } from '../../../cx-api';
1112
import { CfnDeploymentGroup } from '../codedeploy.generated';
@@ -239,15 +240,11 @@ export class EcsDeploymentGroup extends DeploymentGroupBase implements IEcsDeplo
239240
const cfnSvc = (props.service as ecs.BaseService).node.defaultChild as ecs.CfnService;
240241
if (cfnSvc.deploymentController === undefined ||
241242
(cfnSvc.deploymentController! as ecs.CfnService.DeploymentControllerProperty).type !== ecs.DeploymentControllerType.CODE_DEPLOY) {
242-
throw new Error(
243-
'The ECS service associated with the deployment group must use the CODE_DEPLOY deployment controller type',
244-
);
243+
throw new ValidationError('The ECS service associated with the deployment group must use the CODE_DEPLOY deployment controller type', this);
245244
}
246245

247246
if (cfnSvc.taskDefinition !== (props.service as ecs.BaseService).taskDefinition.family) {
248-
throw new Error(
249-
'The ECS service associated with the deployment group must specify the task definition using the task definition family name only. Otherwise, the task definition cannot be updated in the stack',
250-
);
247+
throw new ValidationError('The ECS service associated with the deployment group must specify the task definition using the task definition family name only. Otherwise, the task definition cannot be updated in the stack', this);
251248
}
252249
}
253250

@@ -278,7 +275,7 @@ export class EcsDeploymentGroup extends DeploymentGroupBase implements IEcsDeplo
278275
ignoreAlarmConfiguration: props.ignoreAlarmConfiguration,
279276
}),
280277
}),
281-
autoRollbackConfiguration: cdk.Lazy.any({ produce: () => renderAutoRollbackConfiguration(this.alarms, props.autoRollback) }),
278+
autoRollbackConfiguration: cdk.Lazy.any({ produce: () => renderAutoRollbackConfiguration(this, this.alarms, props.autoRollback) }),
282279
});
283280

284281
this._setNameAndArn(resource, this.application);

packages/aws-cdk-lib/aws-codedeploy/lib/host-health-config.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { CfnDeploymentConfig } from './codedeploy.generated';
2+
import { UnscopedValidationError } from '../../core';
23

34
/**
45
* Minimum number of healthy hosts for a server deployment.
@@ -60,7 +61,7 @@ export class MinimumHealthyHostsPerZone {
6061

6162
private constructor(private readonly json: CfnDeploymentConfig.MinimumHealthyHostsProperty) {
6263
if (!Number.isInteger(json.value)) {
63-
throw new Error(`The percentage or count value of minimumHealthyHostsPerZone must be an integer, got: ${json.value}`);
64+
throw new UnscopedValidationError(`The percentage or count value of minimumHealthyHostsPerZone must be an integer, got: ${json.value}`);
6465
}
6566
}
6667

packages/aws-cdk-lib/aws-codedeploy/lib/lambda/custom-deployment-config.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Construct } from 'constructs';
22
import { ILambdaDeploymentConfig } from './deployment-config';
3-
import { Duration, Names, Resource } from '../../../core';
3+
import { Duration, Names, Resource, ValidationError } from '../../../core';
44
import { addConstructMetadata } from '../../../core/lib/metadata-resource';
55
import { AwsCustomResource, AwsCustomResourcePolicy, PhysicalResourceId } from '../../../custom-resources';
66
import { arnForDeploymentConfig, validateName } from '../private/utils';
@@ -163,14 +163,14 @@ export class CustomLambdaDeploymentConfig extends Resource implements ILambdaDep
163163
// Validate the inputs. The percentage/interval limits come from CodeDeploy
164164
private validateParameters(props: CustomLambdaDeploymentConfigProps): void {
165165
if ( !(1 <= props.percentage && props.percentage <= 99) ) {
166-
throw new Error(
166+
throw new ValidationError(
167167
`Invalid deployment config percentage "${props.percentage.toString()}". \
168-
Step percentage must be an integer between 1 and 99.`);
168+
Step percentage must be an integer between 1 and 99.`, this);
169169
}
170170
if (props.interval.toMinutes() > 2880) {
171-
throw new Error(
171+
throw new ValidationError(
172172
`Invalid deployment config interval "${props.interval.toString()}". \
173-
Traffic shifting intervals must be positive integers up to 2880 (2 days).`);
173+
Traffic shifting intervals must be positive integers up to 2880 (2 days).`, this);
174174
}
175175
}
176176
}

packages/aws-cdk-lib/aws-codedeploy/lib/lambda/deployment-group.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ export class LambdaDeploymentGroup extends DeploymentGroupBase implements ILambd
194194
ignoreAlarmConfiguration: props.ignoreAlarmConfiguration,
195195
}),
196196
}),
197-
autoRollbackConfiguration: cdk.Lazy.any({ produce: () => renderAutoRollbackConfiguration(this.alarms, props.autoRollback) }),
197+
autoRollbackConfiguration: cdk.Lazy.any({ produce: () => renderAutoRollbackConfiguration(this, this.alarms, props.autoRollback) }),
198198
});
199199

200200
this._setNameAndArn(resource, this.application);
@@ -240,7 +240,7 @@ export class LambdaDeploymentGroup extends DeploymentGroupBase implements ILambd
240240
@MethodMetadata()
241241
public addPreHook(preHook: lambda.IFunction): void {
242242
if (this.preHook !== undefined) {
243-
throw new Error('A pre-hook function is already defined for this deployment group');
243+
throw new cdk.ValidationError('A pre-hook function is already defined for this deployment group', this);
244244
}
245245
this.preHook = preHook;
246246
this.grantPutLifecycleEventHookExecutionStatus(this.preHook);
@@ -255,7 +255,7 @@ export class LambdaDeploymentGroup extends DeploymentGroupBase implements ILambd
255255
@MethodMetadata()
256256
public addPostHook(postHook: lambda.IFunction): void {
257257
if (this.postHook !== undefined) {
258-
throw new Error('A post-hook function is already defined for this deployment group');
258+
throw new cdk.ValidationError('A post-hook function is already defined for this deployment group', this);
259259
}
260260
this.postHook = postHook;
261261
this.grantPutLifecycleEventHookExecutionStatus(this.postHook);

packages/aws-cdk-lib/aws-codedeploy/lib/private/utils.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import { Construct } from 'constructs';
12
import { IPredefinedDeploymentConfig } from './predefined-deployment-config';
23
import * as cloudwatch from '../../../aws-cloudwatch';
3-
import { Token, Stack, ArnFormat, Arn, Fn, Aws, IResource } from '../../../core';
4+
import { Token, Stack, ArnFormat, Arn, Fn, Aws, IResource, ValidationError } from '../../../core';
45
import { IBaseDeploymentConfig } from '../base-deployment-config';
56
import { CfnDeploymentGroup } from '../codedeploy.generated';
67
import { AutoRollbackConfig } from '../rollback-config';
@@ -95,7 +96,7 @@ enum AutoRollbackEvent {
9596
DEPLOYMENT_STOP_ON_REQUEST = 'DEPLOYMENT_STOP_ON_REQUEST',
9697
}
9798

98-
export function renderAutoRollbackConfiguration(alarms: cloudwatch.IAlarm[], autoRollbackConfig: AutoRollbackConfig = {}):
99+
export function renderAutoRollbackConfiguration(scope: Construct, alarms: cloudwatch.IAlarm[], autoRollbackConfig: AutoRollbackConfig = {}):
99100
CfnDeploymentGroup.AutoRollbackConfigurationProperty | undefined {
100101
const events = new Array<string>();
101102

@@ -115,9 +116,9 @@ CfnDeploymentGroup.AutoRollbackConfigurationProperty | undefined {
115116
if (alarms.length > 0) {
116117
events.push(AutoRollbackEvent.DEPLOYMENT_STOP_ON_ALARM);
117118
} else if (autoRollbackConfig.deploymentInAlarm === true) {
118-
throw new Error(
119+
throw new ValidationError(
119120
"The auto-rollback setting 'deploymentInAlarm' does not have any effect unless you associate " +
120-
'at least one CloudWatch alarm with the Deployment Group');
121+
'at least one CloudWatch alarm with the Deployment Group', scope);
121122
}
122123
}
123124

packages/aws-cdk-lib/aws-codedeploy/lib/server/deployment-group.ts

+4-5
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,7 @@ export class InstanceTagSet {
100100

101101
constructor(...instanceTagGroups: InstanceTagGroup[]) {
102102
if (instanceTagGroups.length > 3) {
103-
throw new Error('An instance tag set can have a maximum of 3 instance tag groups, ' +
104-
`but ${instanceTagGroups.length} were provided`);
103+
throw new cdk.UnscopedValidationError(`An instance tag set can have a maximum of 3 instance tag groups, but ${instanceTagGroups.length} were provided`);
105104
}
106105
this._instanceTagGroups = instanceTagGroups;
107106
}
@@ -297,7 +296,7 @@ export class ServerDeploymentGroup extends DeploymentGroupBase implements IServe
297296
this.loadBalancers = props.loadBalancers || (props.loadBalancer ? [props.loadBalancer]: undefined);
298297

299298
if (this.loadBalancers && this.loadBalancers.length === 0) {
300-
throw new Error('loadBalancers must be a non-empty array');
299+
throw new cdk.ValidationError('loadBalancers must be a non-empty array', this);
301300
}
302301

303302
for (const asg of this._autoScalingGroups) {
@@ -331,7 +330,7 @@ export class ServerDeploymentGroup extends DeploymentGroupBase implements IServe
331330
ignoreAlarmConfiguration: props.ignoreAlarmConfiguration,
332331
}),
333332
}),
334-
autoRollbackConfiguration: cdk.Lazy.any({ produce: () => renderAutoRollbackConfiguration(this.alarms, props.autoRollback) }),
333+
autoRollbackConfiguration: cdk.Lazy.any({ produce: () => renderAutoRollbackConfiguration(this, this.alarms, props.autoRollback) }),
335334
terminationHookEnabled: props.terminationHook,
336335
});
337336

@@ -496,7 +495,7 @@ export class ServerDeploymentGroup extends DeploymentGroupBase implements IServe
496495
});
497496
}
498497
} else {
499-
throw new Error('Cannot specify both an empty key and no values for an instance tag filter');
498+
throw new cdk.ValidationError('Cannot specify both an empty key and no values for an instance tag filter', this);
500499
}
501500
}
502501
}

0 commit comments

Comments
 (0)