Home > Article > Backend Development > Go - Error. Unable to unpack custom error type
php editor Xigua introduces to you: In Go language, when we use custom error types, we sometimes encounter "Error. Unable to unpack custom error type" question. This problem usually occurs when we try to pass custom error types to other functions or methods. While this may seem like a tricky problem, there are actually several ways to go about it. In this article, we will explore the causes of this problem and provide solutions to help you solve this problem.
I'm trying to use the go stdlib package errors to unpack a custom error type using errors.as
, but it seems the check is failing and I can't extract the underlying error .
I extracted a minimal reproducible example:
package main import ( "errors" "fmt" ) type myError struct { err error } func (m myError) Error() string { return fmt.Sprintf("my error: %s", m.err) } func retError() error { return &myError{errors.New("wrapped")} } func main() { var m myError if err := retError(); errors.As(err, &m) { fmt.Println("unwrapped", m.err) } else { fmt.Println(err) } }
https://go.dev/play/p/i7bnk4-rdib - Examples on the go playground. If launched, it prints "my error: wrapping" instead of the expected "unwrapped wrapping".
The example in theerrors.as
documentation works, I can't seem to understand what I'm doing wrong - I pass *myerror
to errors.as
and that seems to be Correct (because passing myerror
causes a panic: target must be a non-zero pointer
, which is expected). instead of:
func reterror() error { return &myerror{errors.new("wrapped")} }
Do:
func retError() error { return myError{errors.New("wrapped")} }
The above is the detailed content of Go - Error. Unable to unpack custom error type. For more information, please follow other related articles on the PHP Chinese website!