diff --git a/internal/hcclient/error_framework.go b/internal/hcclient/error_framework.go new file mode 100644 index 000000000..fd0a80885 --- /dev/null +++ b/internal/hcclient/error_framework.go @@ -0,0 +1,56 @@ +package hcclient + +import ( + "errors" + "fmt" + + "github.com/hashicorp/terraform-plugin-framework/diag" + + "github.com/hetznercloud/hcloud-go/hcloud" +) + +func APIErrorDiagnostic(resource string, err error) diag.Diagnostics { + var diagnostics diag.Diagnostics + var hcloudErr hcloud.Error + + if errors.As(err, &hcloudErr) { + if hcloud.IsError(hcloudErr, hcloud.ErrorCodeInvalidInput) { + ie := hcloudErr.Details.(hcloud.ErrorDetailsInvalidInput) + for _, v := range ie.Fields { + diagnostics.AddError( + "Invalid field in API request", + fmt.Sprintf( + `An invalid field was encountered while doing the request to %s. The field might not map 1:1 to your terraform resource. + +%s => %s + +Error code: %s +`, + resource, v.Name, v.Messages, hcloudErr.Code, + )) + } + return diagnostics + } + + diagnostics.AddError( + fmt.Sprintf("Request to %s failed", resource), + fmt.Sprintf( + `An unexpected error was encountered while doing the request to %s. +%s + +Error code: %s`, + resource, hcloudErr.Message, hcloudErr.Code, + ), + ) + return diagnostics + } + + diagnostics.AddError( + fmt.Sprintf("Request to %s failed", resource), + fmt.Sprintf( + "An unexpected error was encountered while doing the request to %s.\n\n%s\n", + resource, err.Error(), + ), + ) + return diagnostics +} diff --git a/internal/hcclient/error_framework_test.go b/internal/hcclient/error_framework_test.go new file mode 100644 index 000000000..6326d1d1e --- /dev/null +++ b/internal/hcclient/error_framework_test.go @@ -0,0 +1 @@ +package hcclient diff --git a/internal/hcclient/error.go b/internal/hcclient/error_sdk.go similarity index 100% rename from internal/hcclient/error.go rename to internal/hcclient/error_sdk.go diff --git a/internal/hcclient/error_test.go b/internal/hcclient/error_sdk_test.go similarity index 100% rename from internal/hcclient/error_test.go rename to internal/hcclient/error_sdk_test.go