Skip to content

Commit

Permalink
add FromError func
Browse files Browse the repository at this point in the history
Signed-off-by: Cassandra Coyle <[email protected]>
  • Loading branch information
cicoyle committed Dec 18, 2023
1 parent cbfa8a5 commit 31585da
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,20 @@ func (e *Error) AddDetails(details ...proto.Message) *Error {
return e
}

// FromError takes in an error and returns back the kitError if it's that type under the hood
func FromError(err error) (*Error, bool) {
if err == nil {
return nil, false
}

kitErr, ok := err.(Error)
if ok {
return &kitErr, ok
}

return nil, false
}

/*** GRPC Methods ***/

// GRPCStatus returns the gRPC status.Status object.
Expand Down
26 changes: 26 additions & 0 deletions errors/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -942,3 +942,29 @@ func containsType(types []string, target string) bool {
}
return false
}

func TestFromError(t *testing.T) {
result, ok := FromError(nil)
if result != nil || ok {
t.Errorf("Expected result to be nil and ok to be false, got result: %v, ok: %t", result, ok)
}

kitErr := Error{
grpcCode: grpcCodes.ResourceExhausted,
httpCode: http.StatusTeapot,
message: "fake_message",
tag: "DAPR_FAKE_TAG",
details: []proto.Message{},
}

result, ok = FromError(kitErr)
if !ok || !reflect.DeepEqual(result, &kitErr) {
t.Errorf("Expected result to be %#v and ok to be true, got result: %#v, ok: %t", &kitErr, result, ok)
}

var nonKitError error
result, ok = FromError(nonKitError)
if result != nil || ok {
t.Errorf("Expected result to be nil and ok to be false, got result: %#v, ok: %t", result, ok)
}
}

0 comments on commit 31585da

Please sign in to comment.