Created
December 16, 2020 15:07
-
-
Save Nydan/db010e6f1ee7d5a72e2b41c37bdc5a15 to your computer and use it in GitHub Desktop.
Go 1.13 errors samples.
This file contains 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 ( | |
"errors" | |
"fmt" | |
) | |
var ErrInput = errors.New("wrong input") | |
var ErrConfig = errors.New("invalid config") | |
type InputError struct { | |
Name string | |
Err error | |
} | |
func (i *InputError) Error() string { | |
return i.Name | |
} | |
func (i *InputError) Unwrap() error { | |
return i.Err | |
} | |
func main() { | |
// With Unwrap method from `InputError`, `errors.Is()` is able to detect the `ErrInput`. | |
// Commenting the `UnWrap` method will make `errors.Is()` returning false. | |
err := setInputError("InvalidError type with err equals to ErrInput", ErrInput) | |
if errors.Is(err, ErrInput) { | |
fmt.Println("err var is ErrInput") | |
} | |
// var with type `*InputError` is required to be defined if you want to check | |
// the error is the same type of `*InputError`. | |
var e *InputError | |
if errors.As(err, &e) { | |
fmt.Println("err type is InputError") | |
} | |
// Wrapping an error with `%w` makes it available to `errors.Is` and `errors.As` | |
err = fmt.Errorf("error fmt: %w", ErrConfig) | |
if errors.Is(err, ErrConfig) { | |
fmt.Println("fmt.Errorf available to errors.Is") | |
} | |
// When nesting the error, `error.Is` still able to check the root err to be unwrapped. | |
errNested := fmt.Errorf("second err %w", err) | |
if errors.Is(errNested, ErrConfig) { | |
fmt.Println("nested err is checked") | |
} | |
// errors.As and errors.Is going to find any match error from the wrapped error. | |
err = setInputError("first error", ErrInput) | |
errFmt := fmt.Errorf("Err with InputErr and ErrInput as it err. %w", err) | |
if errors.As(errFmt, &e) { | |
fmt.Println("errors.As able to detect the InputError type") | |
} | |
if errors.Is(errFmt, ErrInput) { | |
fmt.Println("error.Is still able to detect the Err from InputError") | |
} | |
} | |
func setInputError(name string, err error) error { | |
return &InputError{ | |
Name: name, | |
Err: err, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment