简体   繁体   中英

Is it possible to access the fields of a 'DNSError' struct embedded within an 'OpError' struct from the Go 'net' package?

I am starting an SSH client connection in Go and I am trying to access detailed error data when an error is returned.

I am currently using this code:

client, err := ssh.Dial("tcp", "unknownserver:22", config)
if err != nil {
    if oerr, ok := err.(*net.OpError); ok {
        a := oerr.Err
        fmt.Printf("%#v\n", a)
    }
    log.Fatal("Failed to dial: " + err.Error())
}

which returns these two lines of error data:

&net.DNSError{Err:"no such host", Name:"unknownserver", Server:"", IsTimeout:false, IsTemporary:false}
2016/06/23 11:59:00 Failed to dial: dial tcp: lookup unknownserver: no such host

I am trying to print the contents of the Name field inside net.DNSError by using this:

fmt.Println(a.Name)

however when attempting to compile the code I get this error:

a.Name undefined (type error has no field or method Name)

If oerr is a struct of type net.OpError and oerr.Err is a struct of type net.DNSError and has fields {Err:"no such host", Name:"unknownserver", Server:"", IsTimeout:false, IsTemporary:false} , is it possible to access the struct's fields? Or am I misunderstanding a key concept here?

Thanks,

-Martin

Use a second type assertion conditional:

client, err := ssh.Dial("tcp", "unknownserver:22", config)
if err != nil {
    if oerr, ok := err.(*net.OpError); ok {
        a := oerr.Err
        if d, ok := a.(*net.DNSError); ok {
            fmt.Println(d.Name)
        }
        fmt.Printf("%#v\n", a)
    }
    log.Fatal("Failed to dial: " + err.Error())
}

The first type-assertion sets oerr as a *net.OpError , but the Err field of that structure is of type error , which is a built-in interface type (so it has no fields). To access the fields of that error, you first have to assert that it's a structure (specifically, the *net.DNSError structure you want), then you can access the (exported) fields of that structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM