Skip to content

Commit

Permalink
create APIErrorDiagnostic helper
Browse files Browse the repository at this point in the history
  • Loading branch information
jooola committed Sep 19, 2023
1 parent 2a407c8 commit 0d83e80
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
56 changes: 56 additions & 0 deletions internal/hcclient/error_framework.go
Original file line number Diff line number Diff line change
@@ -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
}
1 change: 1 addition & 0 deletions internal/hcclient/error_framework_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package hcclient
File renamed without changes.
File renamed without changes.

0 comments on commit 0d83e80

Please sign in to comment.