英文:
How to throw errors in a lib
问题
我目前正在构建一个用于并发读取/写入/移动文件的小型库。
在进行这个过程中,我遇到了错误处理的问题,这让我思考:
在库内部抛出错误,导致用户的整个应用程序崩溃,还是返回一个错误消息供用户处理?
我想知道在给定的情况下哪种方式最好,以及为什么。
英文:
I am currently building a small lib for reading / writing / moving files around concurrently.
While doing this i ran into the problem of error handling which lead me to think:
should i throw an error inside the lib and have the user's entire app crash, or return an error message for the user to handle ?
I would like to know which is best for the given situation and why.
答案1
得分: 2
我建议阅读《The Go Blog》上关于错误处理和Go的文章Error Handling and Go以及Effective Go,它们介绍了Go错误类型的强大之处。
一般来说,在库/包内部使用panic是可以接受的,但是除非出现致命错误,否则不应该在包外部传播。换句话说,开发人员不应该编写期望从你的库中发生panic的代码。
如果管理错误传播变得繁琐,你可以在内部使用panic。在这种情况下,你可以使用defer/recover处理程序包装你的公共函数,以传递错误。
func Function() (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
// 做一些事情
panic(errors.New("错误消息"))
}
这个示例是从标准库的json
包中改编的,其中内部panic用于清理复杂的嵌套错误处理。
英文:
I recommend reading over The Go Blog article Error Handling and Go and Effective Go on errors, which take a look at the power of Go's error type.
In general panics are okay to use within a library/package, but they should not propagate outside of the package unless there is a fatal error. In other words, developers should never have to write code that expects panics form your library.
You can use panics internally if managing the propagation of errors is tedious. In that case you can wrap your public functions with a defer/recover handler which passes the error
func Function() (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
// Do stuff
panic(errors.New("Error Message"))
}
This sample is adapted from the json
package of the standard library, where internal panics are used to clean up complicated nested error handling.
1: https://blog.golang.org/error-handling-and-go
2: https://golang.org/doc/effective_go.html#errors
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论