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

[Feature]extend stardard errors.New() struct field #43016

Closed
li1234yun opened this issue Dec 5, 2020 · 1 comment
Closed

[Feature]extend stardard errors.New() struct field #43016

li1234yun opened this issue Dec 5, 2020 · 1 comment

Comments

@li1234yun
Copy link

What version of Go are you using (go version)?

go1.15.4

Does this issue reproduce with the latest release?

What operating system and processor architecture are you using (go env)?

go env Output
$ go env

What did you do?

extend standard errors package to include more detail info field to make it more useful.

What did you expect to see?

Maybe consider the following code, it just a suggestion.

/*
Custom Error Handle
*/
package errs

import "fmt"

// Custom Error for convenience extend
type customError struct {
	// Error message as error category string
	Message string
	// Error detail description
	Detail string
	// Wrapped error
	Err error
}

// error interface achieve
func (e *customError) Error() string {
	if e.Detail != "" {
		return fmt.Sprintf("%s: %s", e.Message, e.Detail)
	} else if e.Err != nil {
		return fmt.Sprintf("%s: %v", e.Message, e.Err)
	} else {
		return e.Message
	}
}

// Wrap an error
func (e *customError) WrapE(err error) error {
	e.Err = err
	return e
}

// Wrap string
func (e *customError) WrapS(detail string) error {
	e.Detail = detail
	return e
}

// New custom error
func New(msg string) *customError {
	return &customError{
		Message: msg,
	}
}

// Wrap an error with new detail
func Wrap(e error, msg string) *customError {
	return &customError{
		Message: msg,
		Err:     e,
	}
}

When I handle error, I can define some error category firstly, then I can extend error info.

const CustomError = errs.New("custom error")

func t() error {
    ...

    return CustomError.WrapS("line 3 error")
}

What did you see instead?

Reference only.

@ianlancetaylor
Copy link
Contributor

A lot of people have looked at this kind of issue, and there is no clear consensus on what should be done in this area. So rather than try to provide this in a standard errors package, Go provides the tools that you need to implement it yourself. Or you can use a package like https://pkg.go.dev/github.com/pkg/errors.

Closing because as is this issue isn't going to lead to any changes. Please comment if you disagree. If you want to make changes here, the first step is to build a consensus.

@golang golang locked and limited conversation to collaborators Dec 5, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants