duanjie6912 2017-06-05 20:49
浏览 18

如何在库中引发错误

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条回答 默认 最新

  • donglu3243 2017-06-08 14:04
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效