运行 Go 代码时出现运行时错误。

huangapple go评论93阅读模式
英文:

Runtime error while running go code

问题

我正在尝试运行一个简单的 Golang 代码。

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("sudo", "ls")
    out, err := cmd.Output()
    fmt.Printf("%s", string(out))
    fmt.Printf("%s", err.Error())
}

我得到了以下错误:

$ go run blah.go
    blah.go
    utils.go
    weave_help_test.go
    panic: runtime error: invalid memory address or nil pointer dereference
    [signal 0xb code=0x1 addr=0x20 pc=0x400dc1]

    goroutine 1 [running]:
    runtime.panic(0x4b32a0, 0x5b1fc8)
        /usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
    main.main()
        /home/Abhishek/go/src/github.com/blah.go:12 +0x1c1
    exit status 2

我该如何调试它?

$ go version
go version go1.2.1 linux/amd64
英文:

I am trying to run a simple golang code

$ cat blah.go
package main

import (
        "fmt"
        "os/exec"
)

func main() {
        cmd := exec.Command("sudo","ls")
        out, err := cmd.Output()
        fmt.Printf("%s", string(out))
        fmt.Printf("%s", err.Error())
}

I am getting:

$ go run blah.go
    blah.go
    utils.go
    weave_help_test.go
    panic: runtime error: invalid memory address or nil pointer dereference
    [signal 0xb code=0x1 addr=0x20 pc=0x400dc1]

    goroutine 1 [running]:
    runtime.panic(0x4b32a0, 0x5b1fc8)
        /usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
    main.main()
        /home/Abhishek/go/src/github.com/blah.go:12 +0x1c1
    exit status 2

How should I debug it?

$ go version
go version go1.2.1 linux/amd64

答案1

得分: 5

从运行命令返回的错误对象为nil(这是好的!这意味着它成功了!)。但是你正在访问err.Error(),在一个nil对象上调用它会导致panic。

所以:

a. 检查err是否为nil

b. 你可以直接打印它,不需要调用err.Error()

也就是说,你的代码应该像这样:

    out, err := cmd.Output()
    if err != nil {
       fmt.Println("运行命令时出错:", err)
       return
       //或者在这里甚至触发panic
    }
    // 只有当err为nil时才会执行到这里
    fmt.Printf("%s", string(out))
英文:

the error object returned from the running the command is nil (which is good! that means it succeeded!). But you are accessing err.Error() which on a nil object would result in just that panic.

So

a. check if err is nil

b. you can just print it, no need to call err.Error()

i.e. your code should look like this:

    out, err := cmd.Output()
    if err != nil {
       fmt.Println("Error running command:", err)
       return
       //or even panic here
    }
    // we only get here if err is nil
    fmt.Printf("%s", string(out))

huangapple
  • 本文由 发表于 2015年2月26日 13:27:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/28735087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定