Home  >  Article  >  Backend Development  >  Go - Error. Unable to unpack custom error type

Go - Error. Unable to unpack custom error type

王林
王林forward
2024-02-09 16:45:18843browse

Go - 错误。无法解包自定义错误类型

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.

Question content

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 the errors.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).

Solution

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete