Skip to content

Commit

Permalink
🧹 Use extra Error type for 'object not found'
Browse files Browse the repository at this point in the history
This way, we can check for specific cases where resources weren't found.

Signed-off-by: Christian Zunker <[email protected]>
  • Loading branch information
czunker committed Oct 24, 2022
1 parent a55db2c commit ada9fc3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
12 changes: 12 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@
"processes.list"
],
},
{
"name": "cnquery-run-k8s-pod",
"type": "go",
"request": "launch",
"program": "${workspaceRoot}/apps/cnquery/cnquery.go",
"args": [
"run",
"k8s",
"-c",
"k8s.pod(name: 'passing-pod-yaml', namespace: 'test-vanish'){ name }"
],
},
{
"name": "cnquery-run-admission",
"type": "go",
Expand Down
11 changes: 9 additions & 2 deletions resources/packs/k8s/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ import (
"k8s.io/apimachinery/pkg/runtime"
)

type K8sObjectNotFound struct{}

func (e *K8sObjectNotFound) Error() string {
return "could not find k8s resource"
}

func k8sProvider(t providers.Instance) (k8s_provider.KubernetesProvider, error) {
at, ok := t.(k8s_provider.KubernetesProvider)
if !ok {
Expand Down Expand Up @@ -241,7 +247,8 @@ func initNamespacedResource[T K8sNamespacedObject](
}
}

return args, *new(T), fmt.Errorf("not found")
// the error K8sObjectNotFound is checked by cnspec
return args, *new(T), &K8sObjectNotFound{}
}

func initResource[T K8sObject](
Expand Down Expand Up @@ -308,5 +315,5 @@ func initResource[T K8sObject](
}
}

return nil, *new(T), fmt.Errorf("not found")
return nil, *new(T), &K8sObjectNotFound{}
}
2 changes: 1 addition & 1 deletion resources/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ func (ctx *Runtime) CreateResourceWithID(name string, id string, args ...interfa
// with the `Id` field set to look up an existing resource
res, err := r.Factory(ctx, argsMap)
if err != nil {
return nil, errors.New("failed to create resource '" + name + "': " + err.Error())
return nil, fmt.Errorf("failed to create resource '%s': %w", name, err)
}
if res == nil {
return nil, errors.New("resource factory produced a nil result for resource '" + name + "'")
Expand Down

0 comments on commit ada9fc3

Please sign in to comment.