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

create a common error type with unwrap capability #483

Closed
chappjc opened this issue Jun 15, 2020 · 1 comment
Closed

create a common error type with unwrap capability #483

chappjc opened this issue Jun 15, 2020 · 1 comment

Comments

@chappjc
Copy link
Member

chappjc commented Jun 15, 2020

We should have a dex error type that works well with the Go 1.13 error handling functions, as summarized in decred/dcrd#2181

The described approach is what I did for the error type used in the server/db/drivers/pg package that implements Unwrap. This could be the basis for such a type, dex.DexError perhaps:

// DetailedError pairs an Error with details.
type DetailedError struct {
wrapped error
detail string
}
// Error satisfies the error interface, combining the wrapped error message with
// the details.
func (e DetailedError) Error() string {
return e.wrapped.Error() + ": " + e.detail
}
// Unwrap returns the wrapped error, allowing errors.Is and errors.As to work.
func (e DetailedError) Unwrap() error {
return e.wrapped
}
// NewDetailedError wraps the provided Error with details in a DetailedError,
// facilitating the use of errors.Is and errors.As via errors.Unwrap.
func NewDetailedError(err error, detail string) DetailedError {
return DetailedError{
wrapped: err,
detail: detail,
}
}

Usage example in the unit test:

func TestDetailedError(t *testing.T) {
// Ensure that DetailedError.Unwrap is working via errors.Is.
detail := "blah"
detailed := NewDetailedError(errTooManyRows, detail)
if !errors.Is(detailed, errTooManyRows) {
t.Errorf("Failed to recognize this NewDetailedError as errTooManyRows.")
}
expectedErr := errTooManyRows.Error() + ": " + detail
if detailed.Error() != expectedErr {
t.Errorf("Wrong error message. Got %s, expected %s", detailed.Error(), expectedErr)
}
}

Originally raised by @JoeGruffins in #477 (comment)

@chappjc
Copy link
Member Author

chappjc commented Jun 26, 2020

Resolved by #484, but it still needs to be put into wider use.

@chappjc chappjc closed this as completed Jun 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant