// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
fmt.Errorf(format string, a ...interface{}) error
OR
// New returns an error that formats as the given text.
errors.New(text string) error
**评论:**
kpurdon:
Acidic92:They are (nearly) identical under the hood. So if you need to format your error message
fmt.Errorf()
, if you don'terrors.New()
.https://golang.org/src/fmt/print.go#L204 https://golang.org/src/errors/errors.go#L9
As a side note https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully is a great read on errors.
bgeyts667:My guess:
Speed = errors.New() More Functionality = fmt.Errorf()
Acidic92:They are completely identical. The only difference is that Errorf allows one to format their error message.
Unless you mean, which one to use from code style point of view. If so, then I'd propose to always use custom errors types :)
bgeyts667:Custom error types that fall under the error interface you mean?
Acidic92:Yes, correct. This way you can provide more information about the error and distinguish one error kind from another on the type level.
goboy123:I've explored the depths of Golang (as far as I know), and I understand the fundamentals of interfaces, but the only two things I've never used in my code: My own interfaces because I'm too scared of when to use them and I don't ever see a need for them (although I may be wrong). And, custom errors.
lukechampine:This helped me a lot.
Orange_Tux:I've switched to just using
pkg/errors
everywhere, since it provides both, as well as wrapping errors properly. It annoys me (irrationally) when I have to import botherrors
andfmt
to do error handling.
smasher164:A little off-topic, but, i think
fmt.Errorf
is confusing. People, me included, tend to think thatfmt.Errorf()
prints something. Instead it returns an error. A good example is a comment on a PR I got this weekend.I think
errors.Newf()
is more clear.
winger_sendon:
errors.New(fmt.Sprintf())
is reasonable if you are okay with importing both fmt and errors.
smasher164:Thats what fmt.Errorf is...
Lol facepalm