forked from aliyun/terraform-provider-alicloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
693 lines (607 loc) · 25.8 KB
/
errors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
package alicloud
import (
"strings"
"fmt"
"log"
"runtime"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors"
"github.com/aliyun/aliyun-datahub-sdk-go/datahub"
sls "github.com/aliyun/aliyun-log-go-sdk"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/aliyun/fc-go-sdk"
"github.com/denverdino/aliyungo/common"
)
const (
// common
NotFound = "NotFound"
WaitForTimeout = "WaitForTimeout"
ResourceNotFound = "ResourceNotfound"
ServiceUnavailable = "ServiceUnavailable"
// ecs
InstanceNotFound = "Instance.Notfound"
MessageInstanceNotFound = "instance is not found"
EcsThrottling = "Throttling"
EcsInternalError = "InternalError"
// disk
InternalError = "InternalError"
DependencyViolation = "DependencyViolation"
// eip
EipIncorrectStatus = "IncorrectEipStatus"
InstanceIncorrectStatus = "IncorrectInstanceStatus"
HaVipIncorrectStatus = "IncorrectHaVipStatus"
COMMODITYINVALID_COMPONENT = "COMMODITY.INVALID_COMPONENT"
AllocationIdNotFound = "InvalidAllocationId.NotFound"
HasBeenUsedBySnatTable = "InvalidIpStatus.HasBeenUsedBySnatTable"
HasBeenUsedByForwardEntry = "InvalidIpStatus.HasBeenUsedByForwardEntry"
// slb
LoadBalancerNotFound = "InvalidLoadBalancerId.NotFound"
UnsupportedProtocalPort = "UnsupportedOperationonfixedprotocalport"
ListenerNotFound = "The specified resource does not exist"
ListenerAlreadyExists = "ListenerAlreadyExists"
SlbOrderFailed = "OrderFailed"
VServerGroupNotFoundMessage = "The specified VServerGroupId does not exist"
RspoolVipExist = "RspoolVipExist"
InvalidParameter = "InvalidParameter"
InvalidRuleIdNotFound = "InvalidRuleId.NotFound"
RuleDomainExist = "DomainExist"
BackendServerConfiguring = "BackendServer.configuring"
// slb acl
SlbAclNumberOverLimit = "AclNumberOverLimit"
SlbAclInvalidActionRegionNotSupport = "InvalidAction.RegionNotSupport"
SlbAclNotExists = "AclNotExist"
SlbAclEntryEmpty = "AclEntryEmpty"
SlbAclNameExist = "AclNameExist"
SlbTokenIsProcessing = "OperationFailed.TokenIsProcessing"
SlbCACertificateIdNotFound = "CACertificateId.NotFound"
// slb server certificate
SlbServerCertificateIdNotFound = "ServerCertificateId.NotFound"
// security_group
InvalidInstanceIdAlreadyExists = "InvalidInstanceId.AlreadyExists"
InvalidSecurityGroupIdNotFound = "InvalidSecurityGroupId.NotFound"
SgDependencyViolation = "DependencyViolation"
//Nat gateway
NatGatewayInvalidRegionId = "Invalid.RegionId"
DependencyViolationBandwidthPackages = "DependencyViolation.BandwidthPackages"
VswitchStatusError = "VswitchStatusError"
EIP_NOT_IN_GATEWAY = "EIP_NOT_IN_GATEWAY"
InvalidNatGatewayIdNotFound = "InvalidNatGatewayId.NotFound"
InstanceNotExists = "INSTANCE_NOT_EXISTS"
// vpc
VpcQuotaExceeded = "QuotaExceeded.Vpc"
InvalidVpcIDNotFound = "InvalidVpcID.NotFound"
ForbiddenVpcNotFound = "Forbidden.VpcNotFound"
Throttling = "Throttling"
IncorrectVpcStatus = "IncorrectVpcStatus"
IncorrectStatus = "IncorrectStatus"
// NAS
InvalidFileSystemIDNotFound = "InvalidFileSystem.NotFound"
InvalidAccessGroupNotFound = "InvalidAccessGroup.NotFound"
ForbiddenNasNotFound = "Forbidden.NasNotFound"
InvalidMountTargetNotFound = "InvalidMountTarget.NotFound"
InvalidLBidNotFound = "InvalidLBid.NotFound"
VolumeUnavailable = "VolumeUnavailable"
//apigatway
ApiGroupNotFound = "NotFoundApiGroup"
RepeatedCommit = "RepeatedCommit"
ApiNotFound = "NotFoundApi"
NotFoundApp = "NotFoundApp"
NotFoundAuthorization = "NotFoundAuthorization"
NotFoundStage = "NotFoundStage"
NotFoundVpc = "NotFoundVpc"
// vswitch
VswitcInvalidRegionId = "InvalidRegionId.NotFound"
InvalidVswitchIDNotFound = "InvalidVswitchID.NotFound"
TokenProcessing = "OperationFailed.IdempotentTokenProcessing"
//route entry
IncorrectRouteEntryStatus = "IncorrectRouteEntryStatus"
InvalidStatusRouteEntry = "InvalidStatus.RouteEntry"
TaskConflict = "TaskConflict"
RouterEntryForbbiden = "Forbbiden"
RouterEntryConflictDuplicated = "RouterEntryConflict.Duplicated"
InvalidCidrBlockOverlapped = "InvalidCidrBlock.Overlapped"
IncorrectOppositeInterfaceInfoNotSet = "IncorrectOppositeInterfaceInfo.NotSet"
InvalidSnatTableIdNotFound = "InvalidSnatTableId.NotFound"
InvalidSnatEntryIdNotFound = "InvalidSnatEntryId.NotFound"
IncorretSnatEntryStatus = "IncorretSnatEntryStatus"
InvalidRouteEntryNotFound = "InvalidRouteEntry.NotFound"
// Forward
InvalidIpNotInNatgw = "InvalidIp.NotInNatgw"
InvalidForwardTableIdNotFound = "InvalidForwardTableId.NotFound"
InvalidForwardEntryIdNotFound = "InvalidForwardEntryId.NotFound"
// ess
InvalidScalingGroupIdNotFound = "InvalidScalingGroupId.NotFound"
InvalidScheduledTaskIdNotFound = "InvalidScheduledTaskId.NotFound"
IncorrectScalingConfigurationLifecycleState = "IncorrectScalingConfigurationLifecycleState"
IncorrectScalingGroupStatus = "IncorrectScalingGroupStatus"
IncorrectCapacityMaxSize = "IncorrectCapacity.MaxSize"
IncorrectCapacityMinSize = "IncorrectCapacity.MinSize"
ScalingActivityInProgress = "ScalingActivityInProgress"
EssThrottling = "Throttling"
InvalidScalingRuleIdNotFound = "InvalidScalingRuleId.NotFound"
InvalidLifecycleHookIdNotFound = "InvalidLifecycleHookId.NotExist"
InvalidEssAlarmTaskNotFound = "404"
InvalidEssScalingConfigurationIdNotFound = "InvalidScalingConfigurationId.NotFound"
//drds
InvalidDRDSInstanceIdNotFound = "InvalidDRDSInstanceId.NotFound"
//mongodb
InvalidMongoDBInstanceIdNotFound = "InvalidDBInstanceId.NotFound"
InvalidMongoDBNameNotFound = "InvalidDBName.NotFound"
// gpdb
InvalidGpdbNameNotFound = "InvalidDBName.NotFound"
InvalidGpdbInstanceIdNotFound = "InvalidDBInstanceId.NotFound"
InvalidGpdbInstanceStatus = "OperationDenied.DBInstanceStatus"
// rds
InvalidDBInstanceIdNotFound = "InvalidDBInstanceId.NotFound"
InvalidDBNameNotFound = "InvalidDBName.NotFound"
InvalidDBInstanceNameNotFound = "InvalidDBInstanceName.NotFound"
InvalidCurrentConnectionStringNotFound = "InvalidCurrentConnectionString.NotFound"
InvalidRwSplitNetTypeNotFound = "InvalidRwSplitNetType.NotFound"
NetTypeExists = "NetTypeExists"
InvalidAccountNameDuplicate = "InvalidAccountName.Duplicate"
InvalidAccountNameNotFound = "InvalidAccountName.NotFound"
InvalidConnectionStringDuplicate = "InvalidConnectionString.Duplicate"
AtLeastOneNetTypeExists = "AtLeastOneNetTypeExists"
ConnectionOperationDenied = "OperationDenied"
ConnectionConflictMessage = "The requested resource is sold out in the specified zone; try other types of resources or other regions and zones"
DBInternalError = "InternalError"
OperationDeniedDBInstanceStatus = "OperationDenied.DBInstanceStatus"
DBOperationDeniedOutofUsage = "OperationDenied.OutofUsage"
// oss
OssBucketNotFound = "NoSuchBucket"
OssBodyNotFound = "404 Not Found"
NoSuchCORSConfiguration = "NoSuchCORSConfiguration"
NoSuchWebsiteConfiguration = "NoSuchWebsiteConfiguration"
InsufficientBucketPolicyException = "InsufficientBucketPolicyException"
// RAM Instance Not Found
RamInstanceNotFound = "Forbidden.InstanceNotFound"
AliyunGoClientFailure = "AliyunGoClientFailure"
// dns
RecordForbiddenDNSChange = "RecordForbidden.DNSChange"
FobiddenNotEmptyGroup = "Fobidden.NotEmptyGroup"
DomainRecordNotBelongToUser = "DomainRecordNotBelongToUser"
InvalidDomainNotFound = "InvalidDomain.NotFound"
InvalidDomainNameNoExist = "InvalidDomainName.NoExist"
DnsInternalError = "InternalError"
// ram user
DeleteConflictUserGroup = "DeleteConflict.User.Group"
DeleteConflictUserAccessKey = "DeleteConflict.User.AccessKey"
DeleteConflictUserLoginProfile = "DeleteConflict.User.LoginProfile"
DeleteConflictUserMFADevice = "DeleteConflict.User.MFADevice"
DeleteConflictUserPolicy = "DeleteConflict.User.Policy"
// ram mfa
DeleteConflictVirtualMFADeviceUser = "DeleteConflict.VirtualMFADevice.User"
// ram group
DeleteConflictGroupUser = "DeleteConflict.Group.User"
DeleteConflictGroupPolicy = "DeleteConflict.Group.Policy"
// ram role
DeleteConflictRolePolicy = "DeleteConflict.Role.Policy"
EntityNotExistRole = "EntityNotExist.Role"
// ram policy
DeleteConflictPolicyUser = "DeleteConflict.Policy.User"
DeleteConflictPolicyGroup = "DeleteConflict.Policy.Group"
DeleteConflictPolicyVersion = "DeleteConflict.Policy.Version"
//unknown Error
UnknownError = "UnknownError"
// Keypair error
KeyPairNotFound = "InvalidKeyPair.NotFound"
KeyPairServiceUnavailable = "ServiceUnavailable"
// Container
ErrorClusterNotFound = "ErrorClusterNotFound"
// cr
ErrorNamespaceNotExist = "NAMESPACE_NOT_EXIST"
ErrorRepoNotExist = "REPO_NOT_EXIST"
// cdn
ServiceBusy = "ServiceBusy"
// KMS
ForbiddenKeyNotFound = "Forbidden.KeyNotFound"
// RAM
InvalidRamRoleNotFound = "InvalidRamRole.NotFound"
RoleAttachmentUnExpectedJson = "unexpected end of JSON input"
InvalidInstanceIdNotFound = "InvalidInstanceId.NotFound"
RouterInterfaceIncorrectStatus = "IncorrectStatus"
DependencyViolationRouterInterfaceReferedByRouteEntry = "DependencyViolation.RouterInterfaceReferedByRouteEntry"
// CS
ErrorClusterNameAlreadyExist = "ErrorClusterNameAlreadyExist"
ApplicationNotFound = "Not Found"
ApplicationErrorIgnore = "Unable to reach primary cluster manager"
ApplicationConfirmConflict = "Conflicts with unconfirmed updates for operation"
// privatezone
ZoneNotExists = "Zone.NotExists"
ZoneVpcNotExists = "ZoneVpc.NotExists.VpcId"
ZoneVpcExists = "Zone.VpcExists"
RecordInvalidConflict = "Record.Invalid.Conflict"
PvtzInternalError = "InternalError"
PvtzThrottlingUser = "Throttling.User"
PvtzSystemBusy = "System.Busy"
// log
ProjectNotExist = "ProjectNotExist"
IndexConfigNotExist = "IndexConfigNotExist"
IndexAlreadyExist = "IndexAlreadyExist"
LogStoreNotExist = "LogStoreNotExist"
InternalServerError = "InternalServerError"
GroupNotExist = "GroupNotExist"
MachineGroupNotExist = "MachineGroupNotExist"
LogClientTimeout = "Client.Timeout exceeded while awaiting headers"
LogRequestTimeout = "RequestTimeout"
LogConfigNotExist = "ConfigNotExist"
// OTS
OTSObjectNotExist = "OTSObjectNotExist"
SuffixNoSuchHost = "no such host"
OTSStorageServerBusy = "OTSStorageServerBusy"
OTSQuotaExhausted = "OTSQuotaExhausted"
OTSQuotaFrequentMsg = "Too frequent table operations."
OTSInternalServerError = "OTSInternalServerError"
OTSServerBusy = "OTSServerBusy"
OTSPartitionUnavailable = "OTSPartitionUnavailable"
OTSTimeout = "OTSTimeout"
OTSServerUnavailable = "OTSServerUnavailable"
OTSRowOperationConflict = "OTSRowOperationConflict"
OTSTableNotReady = "OTSTableNotReady"
OTSNotEnoughCapacityUnit = "OTSNotEnoughCapacityUnit"
// FC
ServiceNotFound = "ServiceNotFound"
FunctionNotFound = "FunctionNotFound"
TriggerNotFound = "TriggerNotFound"
AccessDenied = "AccessDenied"
// Vpn
VpnNotFound = "InvalidVpnGatewayInstanceId.NotFound"
VpnForbidden = "Forbidden"
VpnForbiddenRelease = "ForbiddenRelease"
VpnForbiddenSubUser = "Forbbiden.SubUser"
CgwNotFound = "InvalidCustomerGatewayInstanceId.NotFound"
ResQuotaFull = "Resource.QuotaFull"
VpnConnNotFound = "InvalidVpnConnectionInstanceId.NotFound"
InvalidIpAddress = "InvalidIpAddress.AlreadyExist"
SslVpnServerNotFound = "InvalidSslVpnServerId.NotFound"
SslVpnClientCertNotFound = "InvalidSslVpnClientCertId.NotFound"
VpnConfiguring = "VpnGateway.Configuring"
VpnInvalidSpec = "InvalidSpec.NotFound"
VpnEnable = "enable"
// CEN
OperationBlocking = "Operation.Blocking"
ParameterCenInstanceIdNotExist = "ParameterCenInstanceId"
CenQuotaExceeded = "QuotaExceeded.CenCountExceeded"
InvalidCenInstanceStatus = "InvalidOperation.CenInstanceStatus"
InvalidChildInstanceStatus = "InvalidOperation.ChildInstanceStatus"
ParameterInstanceIdNotExist = "ParameterInstanceId"
ForbiddenRelease = "Forbidden.Release"
InvalidCenBandwidthLimitsNotZero = "InvalidOperation.CenBandwidthLimitsNotZero"
ParameterBwpInstanceId = "ParameterBwpInstanceId"
InvalidBwpInstanceStatus = "InvalidOperation.BwpInstanceStatus"
InvalidBwpBusinessStatus = "InvalidOperation.BwpBusinessStatus"
ParameterIllegal = "ParameterIllegal"
ParameterIllegalCenInstanceId = "ParameterIllegal.CenInstanceId"
InstanceNotExist = "Instance.NotExist"
NotFoundRoute = "InvalidOperation.NotFoundRoute"
InvalidStateForOperationMsg = "not in a valid state for the operation"
InstanceNotExistMsg = "The instance is not exist"
// snapshot
SnapshotNotFound = "InvalidSnapshotId.NotFound"
// kv-store
InvalidKVStoreInstanceIdNotFound = "InvalidInstanceId.NotFound"
// MNS
QueueNotExist = "QueueNotExist"
TopicNotExist = "TopicNotExist"
SubscriptionNotExist = "SubscriptionNotExist"
//HaVip
InvalidHaVipIdNotFound = "InvalidHaVipId.NotFound"
InvalidVipStatus = "InvalidVip.Status"
IncorrectHaVipStatus = "IncorrectHaVipStatus"
//Cas
CertNotExist = "CertNotExist"
InvalidPrivateIpAddressDuplicated = "InvalidPrivateIpAddress.Duplicated"
// Elasticsearch
InstanceActivating = "InstanceActivating"
ESInstanceNotFound = "InstanceNotFound"
ESMustChangeOneResource = "MustChangeOneResource"
ESCssCheckUpdowngradeError = "CssCheckUpdowngradeError"
// Ddoscoo
DdoscooInstanceNotFound = "InstanceNotFound"
InvalidDdoscooInstance = "ddos_coop3301"
//nacl
NetworkAclNotFound = "InvalidNetworkAcl.NotFound"
//Actiontrail
InvalidTrailNotFound = "TrailNotFoundException"
TrailNeedRamAuthorize = "NeedRamAuthorize"
)
var SlbIsBusy = []string{"SystemBusy", "OperationBusy", "ServiceIsStopping", "BackendServer.configuring", "ServiceIsConfiguring"}
var EcsNotFound = []string{"InvalidInstanceId.NotFound", "Forbidden.InstanceNotFound"}
var DiskInvalidOperation = []string{"IncorrectDiskStatus", "IncorrectInstanceStatus", "OperationConflict", InternalError, "InvalidOperation.Conflict", "IncorrectDiskStatus.Initializing"}
var NetworkInterfaceInvalidOperations = []string{"InvalidOperation.InvalidEniState", "InvalidOperation.InvalidEcsState", "OperationConflict", "ServiceUnavailable", "InternalError"}
var OperationDeniedDBStatus = []string{"OperationDenied.DBStatus", OperationDeniedDBInstanceStatus, DBInternalError, DBOperationDeniedOutofUsage}
var DBReadInstanceNotReadyStatus = []string{"OperationDenied.ReadDBInstanceStatus", "OperationDenied.MasterDBInstanceState", "ReadDBInstance.Mismatch"}
var NasNotFound = []string{InvalidMountTargetNotFound, InvalidFileSystemIDNotFound, ForbiddenNasNotFound, InvalidLBidNotFound, VolumeUnavailable}
var SnapshotInvalidOperations = []string{"OperationConflict", "ServiceUnavailable", "InternalError", "SnapshotCreatedDisk", "SnapshotCreatedImage"}
var SnapshotPolicyInvalidOperations = []string{"OperationConflict", "ServiceUnavailable", "InternalError", "SnapshotCreatedDisk", "SnapshotCreatedImage"}
// details at: https://help.aliyun.com/document_detail/27300.html
var OtsTableIsTemporarilyUnavailable = []string{SuffixNoSuchHost, OTSServerBusy, OTSPartitionUnavailable, OTSInternalServerError,
OTSTimeout, OTSServerUnavailable, OTSRowOperationConflict, OTSTableNotReady, OTSNotEnoughCapacityUnit, OTSQuotaFrequentMsg}
// An Error represents a custom error for Terraform failure response
type ProviderError struct {
errorCode string
message string
}
func (e *ProviderError) Error() string {
return fmt.Sprintf("[ERROR] Terraform Alicloud Provider Error: Code: %s Message: %s", e.errorCode, e.message)
}
func (err *ProviderError) ErrorCode() string {
return err.errorCode
}
func (err *ProviderError) Message() string {
return err.message
}
func GetNotFoundErrorFromString(str string) error {
return &ProviderError{
errorCode: InstanceNotFound,
message: str,
}
}
func NotFoundError(err error) bool {
if e, ok := err.(*WrapErrorOld); ok {
err = e.originError
}
if err == nil {
return false
}
if e, ok := err.(*ComplexError); ok {
if e.Err != nil && strings.HasPrefix(e.Err.Error(), ResourceNotFound) {
return true
}
return NotFoundError(e.Cause)
}
if err == nil {
return false
}
if e, ok := err.(*common.Error); ok &&
(e.Code == InstanceNotFound || e.Code == RamInstanceNotFound || e.Code == NotFound ||
strings.Contains(strings.ToLower(e.Message), MessageInstanceNotFound)) {
return true
}
if e, ok := err.(*errors.ServerError); ok &&
(e.ErrorCode() == InstanceNotFound || e.ErrorCode() == RamInstanceNotFound || e.ErrorCode() == NotFound ||
strings.Contains(strings.ToLower(e.Message()), MessageInstanceNotFound)) {
return true
}
if e, ok := err.(*ProviderError); ok &&
(e.ErrorCode() == InstanceNotFound || e.ErrorCode() == RamInstanceNotFound || e.ErrorCode() == NotFound ||
strings.Contains(strings.ToLower(e.Message()), MessageInstanceNotFound)) {
return true
}
return false
}
func IsExceptedError(err error, expectCode string) bool {
if e, ok := err.(*WrapErrorOld); ok {
err = e.originError
}
if err == nil {
return false
}
if e, ok := err.(*ComplexError); ok {
return IsExceptedError(e.Cause, expectCode)
}
if err == nil {
return false
}
if e, ok := err.(*common.Error); ok && (e.Code == expectCode || strings.Contains(e.Message, expectCode)) {
return true
}
if e, ok := err.(*errors.ServerError); ok && (e.ErrorCode() == expectCode || strings.Contains(e.Message(), expectCode)) {
return true
}
if e, ok := err.(*ProviderError); ok && (e.ErrorCode() == expectCode || strings.Contains(e.Message(), expectCode)) {
return true
}
if e, ok := err.(*sls.Error); ok && (e.Code == expectCode || strings.Contains(e.Message, expectCode)) {
return true
}
if e, ok := err.(oss.ServiceError); ok && (e.Code == expectCode || strings.Contains(e.Message, expectCode)) {
return true
}
if e, ok := err.(datahub.DatahubError); ok && (e.Code == expectCode || strings.Contains(e.Message, expectCode)) {
return true
}
return false
}
func IsExceptedErrors(err error, expectCodes []string) bool {
if e, ok := err.(*WrapErrorOld); ok {
err = e.originError
}
if err == nil {
return false
}
if e, ok := err.(*ComplexError); ok {
return IsExceptedErrors(e.Cause, expectCodes)
}
if err == nil {
return false
}
for _, code := range expectCodes {
if e, ok := err.(*common.Error); ok && (e.Code == code || strings.Contains(e.Message, code)) {
return true
}
if e, ok := err.(*errors.ServerError); ok && (e.ErrorCode() == code || strings.Contains(e.Message(), code)) {
return true
}
if e, ok := err.(*ProviderError); ok && (e.ErrorCode() == code || strings.Contains(e.Message(), code)) {
return true
}
if e, ok := err.(*sls.Error); ok && (e.Code == code || strings.Contains(e.Message, code)) {
return true
}
if e, ok := err.(oss.ServiceError); ok && (e.Code == code || strings.Contains(e.Message, code)) {
return true
}
if e, ok := err.(*fc.ServiceError); ok && (e.ErrorCode == code || strings.Contains(e.ErrorMessage, code)) {
return true
}
if e, ok := err.(datahub.DatahubError); ok && (e.Code == code || strings.Contains(e.Message, code)) {
return true
}
if strings.Contains(err.Error(), code) {
return true
}
}
return false
}
func RamEntityNotExist(err error) bool {
if e, ok := err.(*WrapErrorOld); ok {
err = e.originError
}
if err == nil {
return false
}
if e, ok := err.(*ComplexError); ok {
err = e.Cause
}
if err == nil {
return false
}
if e, ok := err.(*errors.ServerError); ok && strings.Contains(e.ErrorCode(), "EntityNotExist") {
return true
}
return false
}
func GetTimeErrorFromString(str string) error {
return &ProviderError{
errorCode: WaitForTimeout,
message: str,
}
}
func GetNotFoundMessage(product, id string) string {
return fmt.Sprintf("The specified %s %s is not found.", product, id)
}
func GetTimeoutMessage(product, status string) string {
return fmt.Sprintf("Waitting for %s %s is timeout.", product, status)
}
type ErrorSource string
const (
AlibabaCloudSdkGoERROR = ErrorSource("[SDK alibaba-cloud-sdk-go ERROR]")
AliyunLogGoSdkERROR = ErrorSource("[SDK aliyun-log-go-sdk ERROR]")
AliyunDatahubSdkGo = ErrorSource("[SDK aliyun-datahub-sdk-go ERROR]")
AliyunOssGoSdk = ErrorSource("[SDK aliyun-oss-go-sdk ERROR]")
FcGoSdk = ErrorSource("[SDK fc-go-sdk ERROR]")
DenverdinoAliyungo = ErrorSource("[SDK denverdino/aliyungo ERROR]")
AliyunTablestoreGoSdk = ErrorSource("[SDK aliyun-tablestore-go-sdk ERROR]")
ProviderERROR = ErrorSource("[Provider ERROR]")
)
// An Error to wrap the different erros
type WrapErrorOld struct {
originError error
errorSource ErrorSource
errorPath string
message string
suggestion string
}
// BuildWrapError returns a new error that format the origin error and add some message
// action: the operation of the origin error is from, like a API or method
// id: the resource ID of the origin error is from
// source: the origin error is caused by, it should be one of the ErrorSource
// err: the origin error
// suggestion: the advice of how to resolve the origin error
func BuildWrapError(action, id string, source ErrorSource, err error, suggestion string) error {
if err == nil {
return nil
}
if strings.TrimSpace(id) == "" {
id = "New Resource"
} else {
id = fmt.Sprintf("Resource %s", id)
}
wrapError := &WrapErrorOld{
originError: err,
errorSource: source,
message: fmt.Sprintf("%s %s Failed!!!", id, action),
}
_, filepath, line, ok := runtime.Caller(1)
if !ok {
log.Printf("[ERROR] runtime.Caller error in BuildWrapError.")
} else {
// filepath's format is: <gopath>/src/github.com/terraform-providers/terraform-provider-alicloud/alicloud/<resource>.go
parts := strings.Split(filepath, "/")
if len(parts) > 3 {
filepath = strings.Join(parts[len(parts)-3:], "/")
}
wrapError.errorPath = fmt.Sprintf("%s:%d", filepath, line)
}
suggestion = strings.TrimSpace(suggestion)
if suggestion != "" {
wrapError.suggestion = fmt.Sprintf("[Provider Suggestion]: %s.", suggestion)
}
return wrapError
}
func (e *WrapErrorOld) Error() string {
return fmt.Sprintf("[ERROR] %s: %s %s:\n%s\n%s", e.errorPath, e.message, e.errorSource, e.originError.Error(), e.suggestion)
}
// ComplexError is a format error which inclouding origin error, extra error message, error occurred file and line
// Cause: a error is a origin error that comes from SDK, some expections and so on
// Err: a new error is built from extra message
// Path: the file path of error occurred
// Line: the file line of error occurred
type ComplexError struct {
Cause error
Err error
Path string
Line int
}
func (e ComplexError) Error() string {
if e.Cause == nil {
e.Cause = Error("<nil cause>")
}
if e.Err == nil {
return fmt.Sprintf("[ERROR] %s:%d:\n%s", e.Path, e.Line, e.Cause.Error())
}
return fmt.Sprintf("[ERROR] %s:%d: %s:\n%s", e.Path, e.Line, e.Err.Error(), e.Cause.Error())
}
func Error(msg string, args ...interface{}) error {
return fmt.Errorf(msg, args...)
}
// Return a ComplexError which including error occurred file and path
func WrapError(cause error) error {
if cause == nil {
return nil
}
_, filepath, line, ok := runtime.Caller(1)
if !ok {
log.Printf("[ERROR] runtime.Caller error in WrapError.")
return WrapComplexError(cause, nil, "", -1)
}
parts := strings.Split(filepath, "/")
if len(parts) > 3 {
filepath = strings.Join(parts[len(parts)-3:], "/")
}
return WrapComplexError(cause, nil, filepath, line)
}
// Return a ComplexError which including extra error message, error occurred file and path
func WrapErrorf(cause error, msg string, args ...interface{}) error {
if cause == nil && strings.TrimSpace(msg) == "" {
return nil
}
_, filepath, line, ok := runtime.Caller(1)
if !ok {
log.Printf("[ERROR] runtime.Caller error in WrapErrorf.")
return WrapComplexError(cause, Error(msg), "", -1)
}
parts := strings.Split(filepath, "/")
if len(parts) > 3 {
filepath = strings.Join(parts[len(parts)-3:], "/")
}
return WrapComplexError(cause, fmt.Errorf(msg, args...), filepath, line)
}
func WrapComplexError(cause, err error, filepath string, fileline int) error {
return &ComplexError{
Cause: cause,
Err: err,
Path: filepath,
Line: fileline,
}
}
// A default message of ComplexError's Err. It is format to Resource <resource-id> <operation> Failed!!! <error source>
const DefaultErrorMsg = "Resource %s %s Failed!!! %s"
const NotFoundMsg = ResourceNotFound + "!!! %s"
const DefaultTimeoutMsg = "Resource %s %s Timeout!!! %s"
const DeleteTimeoutMsg = "Resource %s Still Exists. %s Timeout!!! %s"
const WaitTimeoutMsg = "Resource %s %s Timeout In %d Seconds. Got: %s Expected: %s !!! %s"
const DataDefaultErrorMsg = "Datasource %s %s Failed!!! %s"
const DefaultDebugMsg = "\n*************** %s Response *************** \n%s\n%s******************************\n\n"
const FailedToReachTargetStatus = "Failed to reach target status. Current status is %s."
const FailedToReachTargetAttribute = "Failed to reach value for target attribute. Current value is %s."