TLDR: There is a function in some library, which does something over network and may fail with error. Error may indicate bad input parameter, invalid credentials, network failure... And... I don't know what else. And that's the question.
How do I know, what errors to expect, to handle, say, network failures properly.
Long version: It is a very common way to handle errors like that in Go code
function f0() (v Value, err Error) {
v2, err := f3()
if err != nil {
return
}
v1, err := f2(v2)
if err != nil {
return
}
v, err = f1(v1)
return
}
It is also very common in Go code to not document type of error returned. Let's not forget about another common idiom in Go
err = errors.New("Boo! I failed") // returns trivial errorString
This leads to the situation where caller of f0()
can get dozens of errors (if f3()
to f1()
in my example also do some calls) which represent conceptually different issues.
How to differentiate between all those errors?
Anything implementing this minimal interface is an error;
type error interface {
Error() string
}
The easy solution is;
type BadCredsError string
func (e BadCredsError) Error() string {
return string(e)
}
Basically, just define your own types and then you can use a type switch or type assertion to determine the specific error types like you see in more OO languages such as C# and Java.
By the way, my sample is like a 2 seconds pseudo code snippet. The go blog discusses far more in depth here; http://blog.golang.org/error-handling-and-go