Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clientdetails: handle error interfaces in Details somewhat #4137

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
66 changes: 66 additions & 0 deletions internal/worker/clienterrors/errors.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package clienterrors

import (
"encoding/json"
"fmt"
"reflect"
)

const (
Expand Down Expand Up @@ -58,6 +60,70 @@ func (e *Error) String() string {
return fmt.Sprintf("Code: %d, Reason: %s, Details: %v", e.ID, e.Reason, e.Details)
}

func ensureNoErrs(v reflect.Value) error {
switch v.Kind() {
case reflect.Interface:
if errIf, ok := v.Interface().(error); ok {
if errIf != nil {
return fmt.Errorf("%v", errIf.Error())
}
}
case reflect.Ptr:
if err := ensureNoErrs(v.Elem()); err != nil {
return err
}
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
if err := ensureNoErrs(v.Field(i)); err != nil {
return err
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mvo5 Do I get this right, that only the first will be returned (same for array and map)? Is this on purpose?

Copy link
Contributor Author

@mvo5 mvo5 Jun 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, only the first is detected right now. We can change that of course, I'm not sure if it's worth it (also I'm not sure this entire PR is the right approach, it's nice in the sense that it does detect the issue now but it still will not catch other cases where we pass something to Details interface{} that is in fact an interface that is not properly serializable to json

I still wonder if we a better appraoch would be:
a) merge #4145 to fix the immedidate issue
b) change Details inteface{} -> Details string or Details []string or Details json.RawMessage (the later would force the caller to serialize). (i.e. ensure passing an err becomes a compile time error instead of a runtime error).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure where the idea comes from that Details should be flexible but then it would be a) and b) with json.RawMessage
Starting with #4145 for now sound perfect 😏

Copy link
Contributor Author

@mvo5 mvo5 Jun 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's probably worth to salvage (some of) the test cases from this PR but otherwise I'm fine closing it (or closing it after (a) and (b) got done). [fwiw, (b) with json.RawMessage might become a bit annoying on the caller side, but I guess we need to try it to see how good/bad it will be :)

}
}
case reflect.Slice, reflect.Array:
for i := 0; i < v.Len(); i++ {
if err := ensureNoErrs(v.Index(i)); err != nil {
return err
}
}
case reflect.Map:
for _, key := range v.MapKeys() {
if err := ensureNoErrs(v.MapIndex(key)); err != nil {
return err
}
}
}
return nil
}

func (e *Error) MarshalJSON() ([]byte, error) {
var details interface{}
switch v := e.Details.(type) {
case error:
details = v.Error()
case []error:
details = make([]string, 0, len(v))
for _, err := range v {
if err != nil {
details = append(details.([]string), err.Error())
}
}
default:
if err := ensureNoErrs(reflect.ValueOf(v)); err != nil {
return nil, fmt.Errorf("found nested error in %+v: %v", e.Details, err)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is probably a bit too terse, maybe found nested error in Details field or something

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the rare cases (none?) where this will happen, I think it's good :-)

}
details = e.Details
}

return json.Marshal(&struct {
ID ClientErrorCode `json:"id"`
Reason string `json:"reason"`
Details interface{} `json:"details,omitempty"`
}{
ID: e.ID,
Reason: e.Reason,
Details: details,
})
}

const (
JobStatusSuccess = "2xx"
JobStatusUserInputError = "4xx"
Expand Down
65 changes: 65 additions & 0 deletions internal/worker/clienterrors/errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package clienterrors_test

import (
"encoding/json"
"fmt"
"testing"

"github.com/stretchr/testify/assert"

"github.com/osbuild/osbuild-composer/internal/worker/clienterrors"
)

type customErr struct{}

func (ce *customErr) Error() string {
return "customErr"
}

func TestErrorInterface(t *testing.T) {
for _, tc := range []struct {
err error
expectedStr string
}{
{fmt.Errorf("some error"), "some error"},
{&customErr{}, "customErr"},
} {
wce := clienterrors.WorkerClientError(2, "reason", tc.err)
assert.Equal(t, fmt.Sprintf("Code: 2, Reason: reason, Details: %s", tc.expectedStr), wce.String())
}
}

func TestErrorJSONMarshal(t *testing.T) {
for _, tc := range []struct {
err interface{}
expectedStr string
}{
{fmt.Errorf("some-error"), `"some-error"`},
{[]error{fmt.Errorf("err1"), fmt.Errorf("err2")}, `["err1","err2"]`},
{"random detail", `"random detail"`},
} {
json, err := json.Marshal(clienterrors.WorkerClientError(2, "reason", tc.err))
assert.NoError(t, err)
assert.Equal(t, fmt.Sprintf(`{"id":2,"reason":"reason","details":%s}`, tc.expectedStr), string(json))
}
}

func TestErrorJSONMarshalDetectsNestedErrs(t *testing.T) {
details := struct {
Unrelated string
NestedErr error
Nested struct {
DeepErr error
}
}{
Unrelated: "unrelated",
NestedErr: fmt.Errorf("some-nested-error"),
Nested: struct {
DeepErr error
}{
DeepErr: fmt.Errorf("deep-err"),
},
}
_, err := json.Marshal(clienterrors.WorkerClientError(2, "reason", details))
assert.Equal(t, `json: error calling MarshalJSON for type *clienterrors.Error: found nested error in {Unrelated:unrelated NestedErr:some-nested-error Nested:{DeepErr:deep-err}}: some-nested-error`, err.Error())
}