如何在库中引发错误

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.

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.