劫持恐慌输出

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

Hijacking panic output

问题

当我的 Golang 应用程序发生 panic 时,它会打印 goroutine 的堆栈跟踪并退出。我想知道是否有一种好的方法可以获取 panic 输出以进行进一步处理。仅仅重定向 stderr 是不够的,因为我们可能希望在其中添加一些错误日志。我只想获取 panic 输出。

英文:

When my golang app is panicking, it is printing go routines stack trace and quiting. I wonder if there is nice way to get panic output for further processing. Redirecting stderr is not enough, because one would like to put some error logs there. I would like to get only panic output.

答案1

得分: 2

你可以使用runtime.Stack函数获取格式化的堆栈跟踪。通过将true作为第二个参数传递,你可以看到所有goroutine的堆栈跟踪。

英文:

You can get a formatted stack trace using the runtime.Stack function. By passing true as the second argument, you can see stack traces of all gouroutines.

答案2

得分: 0

以下是代码的中文翻译:

package main

import (
    "fmt"
)

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("panic:", r)
        }
    }()

    test := []int{1, 2, 3}
    fmt.Println(test[5])
}

使用 deferrecover

你可以在这里阅读更多关于 deferpanicrecover 的信息:http://blog.golang.org/defer-panic-and-recover

英文:
    1 package main
    2 
    3 import (
    4 ›   "fmt"
    5 )
    6 
    7 func main() {
    8 ›   defer func() {
    9 ›   ›   if r := recover(); r != nil {
   10 ›   ›   ›   fmt.Println("panic:", r)                                                                                                                                                                                                 
   11 ›   ›   }
   12 ›   }()
   13 
   14 ›   test := []int{1, 2, 3}
   15 ›   fmt.Println(test[5])
   16 
   17 }

using defer and recover.

http://blog.golang.org/defer-panic-and-recover

huangapple
  • 本文由 发表于 2015年1月20日 16:42:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/28040901.html
匿名

发表评论

匿名网友

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

确定