Skip to content

Commit

Permalink
feat(error-handling): add error modification capability
Browse files Browse the repository at this point in the history
Introduce the From function to allow modification of CustomError
instances with provided options. This enhances flexibility in error
handling by enabling dynamic updates to error attributes.

- Implement From function in customerror.go
- Add tests for From function in customerror_test.go
  • Loading branch information
thalesfsp committed Oct 28, 2024
1 parent 2d42c43 commit 21bad53
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
13 changes: 13 additions & 0 deletions customerror.go
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,19 @@ func To(err error) (*CustomError, bool) {
return cE, true
}

// From modifies the error with the given options.
func From(err error, opts ...Option) error {
if cE, ok := To(err); ok {
for _, opt := range opts {
opt(cE)
}

return cE
}

return err
}

// IsHTTPStatus checks if the error is a `CustomError` with the
// specified HTTP status code.
func IsHTTPStatus(err error, statusCode int) bool {
Expand Down
23 changes: 23 additions & 0 deletions customerror_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,3 +439,26 @@ func Test_CustomError_String(t *testing.T) {

assert.Equal(t, expected, s.String())
}

func Test_From(t *testing.T) {
// Helper function that receives a "throw" custom error and return it as an
// error.
throwIt := func(err error) error {
return err
}

// Create a custom error that will be modified later.
cE := New("An error occurred", WithErrorCode("E1010"), WithStatusCode(http.StatusBadRequest))

// Simulate throwing it.
err := throwIt(cE)

// Ensure the message.
assert.Equal(t, "E1010: An error occurred", cE.Error())

// Modify the error.
newErr := From(err, WithErrorCode("E1011"))

// Ensure changes are applied.
assert.Equal(t, "E1011: An error occurred", newErr.Error())
}

0 comments on commit 21bad53

Please sign in to comment.