I want to print everything in my custom error struct like fmt.Print()
prints any other struct, but since it implements error
it only prints one field, the one I pass out through Error()
.
How can I do this?
I want to print everything in my custom error struct like fmt.Print()
prints any other struct, but since it implements error
it only prints one field, the one I pass out through Error()
.
How can I do this?
You can type assert the error
interface to your custom type. Note that you should, ideally, use the 'comma, ok' idiom when doing so otherwise your application will panic if the type assertion fails.
package main
import "fmt"
type MyError struct {
Status int
Message string
}
func (e MyError) Error() string {
return e.Message
}
func BadThing() error {
return MyError{404, "Not found"}
}
func main() {
err := BadThing()
if err != nil {
if v, ok := err.(MyError); ok {
fmt.Printf("%+v
", v.Status) // or v, or v.Message, etc.
}
fmt.Printf("%v
", err) // Fallback. Can wrap in this in an 'else' if needed.
}
}
Playground - and further reading: http://blog.golang.org/error-handling-and-go