Created
December 12, 2017 20:47
-
-
Save tehmoon/c78936a0a4821cf25ca8f3063c4e1795 to your computer and use it in GitHub Desktop.
Handling errors in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/tehmoon/errors" | |
"fmt" | |
) | |
// This example is similar to "github.com/pkg/errors" from Dave Cheney | |
// The idea is to declare simple error and have them chained using WrapErr | |
// so it's easy to have the complete chain of errors if needed. | |
// Also declaring error variables is useful when comparing errors. | |
var ( | |
ErrBadNumber = errors.Errorf("The number must be between 1 and %d", (1<<16) - 1) | |
ErrParseEnvVar = errors.New("Error parsing env variable") | |
) | |
func envToUint16(env string) (uint16, error) { | |
// parse the env var to integer | |
return 0, errors.WrapErr(ErrBadNumber, ErrParseEnvVar) | |
} | |
func main() { | |
env := "blih" | |
_, err := envToUint16(env) | |
fmt.Println(errors.Wrapf(err, "Error parsing number from env: %s", env)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment