diff --git a/bitbucket/error.go b/bitbucket/error.go new file mode 100644 index 00000000..caba89cd --- /dev/null +++ b/bitbucket/error.go @@ -0,0 +1,26 @@ +package bitbucket + +import ( + "encoding/json" + + "github.com/DrFaust92/bitbucket-go-client" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" +) + +func handleClientError(err error) diag.Diagnostics { + httpErr, ok := err.(bitbucket.GenericSwaggerError) + if ok { + var httpError bitbucket.ModelError + if err := json.Unmarshal(httpErr.Body(), &httpError); err != nil { + return diag.Errorf(string(httpErr.Body())) + } + + return diag.Errorf("%s: %s", httpErr.Error(), httpError.Error_.Message) + } + + if err != nil { + return diag.FromErr(err) + } + + return nil +} diff --git a/bitbucket/resource_branch_restriction.go b/bitbucket/resource_branch_restriction.go index 8d9d2083..adad2687 100644 --- a/bitbucket/resource_branch_restriction.go +++ b/bitbucket/resource_branch_restriction.go @@ -196,8 +196,8 @@ func resourceBranchRestrictionsCreate(ctx context.Context, d *schema.ResourceDat workspace := d.Get("owner").(string) branchRestrictionReq, _, err := brApi.RepositoriesWorkspaceRepoSlugBranchRestrictionsPost(c.AuthContext, *branchRestriction, repo, workspace) - if err != nil { - return diag.FromErr(err) + if diag := handleClientError(err); diag != nil { + return diag } d.SetId(string(fmt.Sprintf("%v", branchRestrictionReq.Id))) @@ -218,8 +218,8 @@ func resourceBranchRestrictionsRead(ctx context.Context, d *schema.ResourceData, return nil } - if err != nil { - return diag.FromErr(err) + if diag := handleClientError(err); diag != nil { + return diag } d.SetId(string(fmt.Sprintf("%v", brRes.Id))) @@ -243,8 +243,8 @@ func resourceBranchRestrictionsUpdate(ctx context.Context, d *schema.ResourceDat *branchRestriction, url.PathEscape(d.Id()), d.Get("repository").(string), d.Get("owner").(string)) - if err != nil { - return diag.FromErr(err) + if diag := handleClientError(err); diag != nil { + return diag } return resourceBranchRestrictionsRead(ctx, d, m) @@ -262,8 +262,8 @@ func resourceBranchRestrictionsDelete(ctx context.Context, d *schema.ResourceDat return nil } - if err != nil { - return diag.FromErr(err) + if diag := handleClientError(err); diag != nil { + return diag } return nil