Skip to content

Commit

Permalink
Add IsMissingNamespaceErr function
Browse files Browse the repository at this point in the history
Checks if the error indicates the namespace for a resource is missing
when trying to create it. In this case the error is NotFound and the
status details reflects the "namespaces" Kind. For example:

{
  "ErrStatus": {
    "status": "Failure",
    "message": "namespaces \"foo\" not found",
    "reason": "NotFound",
    "details": {
      "name": "foo",
      "kind": "namespaces"
    },
    "code": 404
  }
}

Signed-off-by: Tom Pantelis <[email protected]>
  • Loading branch information
tpantelis committed May 4, 2024
1 parent 13acb26 commit 22ee518
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pkg/resource/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,16 @@ func IsNotFoundErr(err error) bool {

return false
}

func IsMissingNamespaceErr(err error) (bool, string) {

Check failure on line 46 in pkg/resource/errors.go

View workflow job for this annotation

GitHub Actions / Go

unnamedResult: consider giving a name to these results (gocritic)
if !apierrors.IsNotFound(err) {
return false, ""
}

var status apierrors.APIStatus
_ = errors.As(err, &status)

d := status.Status().Details

return d != nil && d.Kind == "namespaces" && d.Group == "", d.Name
}
28 changes: 28 additions & 0 deletions pkg/resource/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,31 @@ var _ = Describe("IsNotFoundErr", func() {
})
})
})

var _ = Describe("IsMissingNamespaceErr", func() {
When("the error isn't NotFound", func() {
It("should return false", func() {
ok, _ := resource.IsMissingNamespaceErr(apierrors.NewBadRequest(""))
Expect(ok).To(BeFalse())
})
})

When("the error details specify a namespace", func() {
It("should return true and the name", func() {
ok, name := resource.IsMissingNamespaceErr(apierrors.NewNotFound(schema.GroupResource{
Resource: "namespaces",
}, "missing-ns"))
Expect(ok).To(BeTrue())
Expect(name).To(Equal("missing-ns"))
})
})

When("the error details does not specify a namespace", func() {
It("should return false", func() {
ok, _ := resource.IsMissingNamespaceErr(apierrors.NewNotFound(schema.GroupResource{
Resource: "pods",
}, "missing"))
Expect(ok).To(BeFalse())
})
})
})

0 comments on commit 22ee518

Please sign in to comment.