Go - Error. Unable to unpack custom error type

王林
Release: 2024-02-09 16:45:18
forward
824 people have browsed it

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)
    }
}
Copy after login

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")}
}
Copy after login

Do:

func retError() error {
    return myError{errors.New("wrapped")}
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!