Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created December 19, 2024 17:44
Show Gist options
  • Save Integralist/3b1b8dcba080c980208a8bdd546966fd to your computer and use it in GitHub Desktop.
Save Integralist/3b1b8dcba080c980208a8bdd546966fd to your computer and use it in GitHub Desktop.
[Golang Custom Error Handling] #go #golang
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