Skip to content

Commit

Permalink
WithError return Error and add ToError to return error
Browse files Browse the repository at this point in the history
  • Loading branch information
xgfone committed Mar 26, 2024
1 parent b0c1a43 commit a3be9bf
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
15 changes: 12 additions & 3 deletions http/statuscode/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,13 @@ func (e Error) Error() string {
return e.Err.Error()
}

// WithError returns a new error.
func (e Error) WithError(err error) error {
// WithError returns a new Error.
//
// If err is nil, Code of the returned error is equal to 200.
func (e Error) WithError(err error) Error {
switch _err := err.(type) {
case nil:
return nil
return Error{Code: 200}

case Error:
return _err
Expand All @@ -93,6 +95,13 @@ func (e Error) WithMessage(msg string, args ...interface{}) Error {
return e
}

func (e Error) ToError(err error) error {
if err != nil {
err = e.WithError(err)
}
return err
}

// ServeHTTP implements the interface http.Handler.
func (e Error) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch err := e.Err.(type) {
Expand Down
15 changes: 12 additions & 3 deletions result/code/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,13 @@ func (e Error[T]) WithCtx(ctx any) Error[T] {
return e
}

// WithError returns a new error, which inspects the error code and message from err.
func (e Error[T]) WithError(err error) error {
// WithError returns a new Error, which inspects the error code and message from err.
//
// If err is nil, return an empty Error ZERO.
func (e Error[T]) WithError(err error) Error[T] {
switch _e := err.(type) {
case nil:
return nil
return Error[T]{}

case Error[T]:
return _e
Expand Down Expand Up @@ -96,6 +98,13 @@ func (e Error[T]) WithMessage(msgfmt string, msgargs ...interface{}) Error[T] {
return e
}

func (e Error[T]) ToError(err error) error {
if err != nil {
err = e.WithError(err)
}
return err
}

// Respond sends the error as result.Response by the responder.
func (e Error[T]) Respond(responder any) {
result.Err(e).Respond(responder)
Expand Down
2 changes: 1 addition & 1 deletion result/code/error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
)

func TestError(t *testing.T) {
e := NewError("Ok", "").WithError(errors.New("test")).(Error[string]).
e := NewError("Ok", "").WithError(errors.New("test")).
WithCtx(200).WithMessage("").WithMessage("%s", "msg")

expect := "Ok: msg"
Expand Down

0 comments on commit a3be9bf

Please sign in to comment.