Created
December 19, 2024 17:44
-
-
Save Integralist/3b1b8dcba080c980208a8bdd546966fd to your computer and use it in GitHub Desktop.
[Golang Custom Error Handling] #go #golang
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" | |
"io" | |
) | |
func main() { | |
err := doSomething() | |
fe := &FooError{} | |
if errors.As(err, fe) { | |
fmt.Printf("it's a FooError: %#v\n", fe) // &main.FooError{Op:"doSomething", Err:(*errors.errorString)(0x556720)} | |
fmt.Printf("%#v\n", fe.Op) // "doSomething" | |
fmt.Printf("%#v\n", fe.Err) // &errors.errorString{s:"EOF"} | |
} | |
} | |
type FooError struct { | |
Op string | |
Err error | |
} | |
func (e FooError) Error() string { | |
return fmt.Sprintf("operation %s: %v", e.Op, e.Err) | |
} | |
func (e FooError) Unwrap() error { | |
return e.Err | |
} | |
func doSomething() error { | |
return FooError{ | |
Op: "doSomething", | |
Err: io.EOF, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment