Skip to content

Commit

Permalink
Merge pull request #125 from Nkmol/fix-error-handling-resource-branch…
Browse files Browse the repository at this point in the history
…-restriction

fix(branch-restriction): handle http errors
  • Loading branch information
DrFaust92 authored Dec 22, 2022
2 parents 543095d + ea9d622 commit cc3201f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
26 changes: 26 additions & 0 deletions bitbucket/error.go
Original file line number Diff line number Diff line change
@@ -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
}
16 changes: 8 additions & 8 deletions bitbucket/resource_branch_restriction.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand All @@ -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)))
Expand All @@ -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)
Expand All @@ -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
Expand Down

0 comments on commit cc3201f

Please sign in to comment.