Skip to content

Instantly share code, notes, and snippets.

@ixqbar
Created August 21, 2018 06:16
Show Gist options
  • Save ixqbar/f6a01e7a0ab8fe02f8d9759eb7d9c0eb to your computer and use it in GitHub Desktop.
Save ixqbar/f6a01e7a0ab8fe02f8d9759eb7d9c0eb to your computer and use it in GitHub Desktop.
golang之net.Error

func isCaredNetError(err error) bool {
    netErr, ok := err.(net.Error)
    if !ok {
        return false
    }

    if netErr.Timeout() {
        log.Println("timeout")
        return true
    }

    opErr, ok := netErr.(*net.OpError)
    if !ok {
        return false
    }

    switch t := opErr.Err.(type) {
    case *net.DNSError:
        log.Printf("net.DNSError:%+v", t)
        return true
    case *os.SyscallError:
        log.Printf("os.SyscallError:%+v", t)
        if errno, ok := t.Err.(syscall.Errno); ok {
            switch errno {
            case syscall.ECONNREFUSED:
                log.Println("connect refused")
                return true
            case syscall.ETIMEDOUT:
                log.Println("timeout")
                return true
            }
        }
    }

    return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment