fmt.Errorf() or errors.New()?

agolangf · 2017-06-06 22:00:01 · 6078 次点击    
这是一个分享于 2017-06-06 22:00:01 的资源,其中的信息可能已经有所发展或是发生改变。
// 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:

They are (nearly) identical under the hood. So if you need to format your error message fmt.Errorf(), if you don't errors.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.

Acidic92:

My guess:

Speed = errors.New()
More Functionality = fmt.Errorf()
bgeyts667:

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 :)

Acidic92:

Custom error types that fall under the error interface you mean?

bgeyts667:

Yes, correct. This way you can provide more information about the error and distinguish one error kind from another on the type level.

Acidic92:

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.

goboy123:

This helped me a lot.

https://dave.cheney.net/paste/gocon-spring-2016.pdf

lukechampine:

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 both errors and fmt to do error handling.

Orange_Tux:

A little off-topic, but, i think fmt.Errorf is confusing. People, me included, tend to think that fmt.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.

smasher164:

errors.New(fmt.Sprintf()) is reasonable if you are okay with importing both fmt and errors.

winger_sendon:

Thats what fmt.Errorf is...

smasher164:

Lol facepalm


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

6078 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传