Member-only story
Go Error Best Practices
Create and handle your errors the right way
Being indulged in Go for quite a while and having implemented web-related programs, grpc interfaces, and Operators, I seem to be an advanced beginner now.
However, I am still a novice in production-environmental debugging, which is cumbersome if done by querying logs or error messages. Imagine the scenario that a full-text search is called when the specific location of the error log is missing. Then what happens when those error logs are not only in one place? Yes, my error logs can no longer help me locate the errors quickly and accurately.
Apparently, the lack of the try {…} catch
structure supported by most other high-level languages makes Go’s design on the error handling controversial. And the following code structures are what occur everywhere in Go: each error needs to be processed, and errors are nested layer by layer. As a Java developer for years, you cannot escape but adapt.
a, err := fn()
if err != nil {
return err
}func fn() error {
b, err := fn1()
if err != nil {
…
return err
}
if _, err = fn2(); err != nil {
…
}
}
Nevertheless, we can always step on our predecessors’ shoulders and work out a solution to the difficulties. In the sections below, I am sharing some…