go - 重写goroutine函数并进行恢复

标签 go

我想编写一个恢复goroutine painc的函数,下面的演示为“test1”恢复了goroutine painc,但不支持“test2”,“test3”,“test4”。
我怎样才能编写一个函数来恢复任何goroutine痛苦。

func main() {
    go myGoroutine(test1)
    time.Sleep(10 * time.Second)
}

func myGoroutine(realGoFunc func()) {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println(err)
        }
    }

    realGoFunc()
}

func test1() {
    fmt.Println("test1 come here)
    painc("test1 error")
    fmt.Println("test1 end")
}

func test2(username string) {
    fmt.Println("test2 come here)
    painc("test2 error")
    fmt.Println("test2 end")
}

func test3(userId int64, username string) {
    fmt.Println("test3 come here)
    painc("test3 error")
    fmt.Println("test3 end")
}

func test4(user *User) {
    fmt.Println("test4 come here)
    painc("test4 error")
    fmt.Println("test4 end")
}

最佳答案

在您的情况下,可能(但不太好)选择使用上下文:

type User struct {
    name string
    uid  int64
}


func main() {

    user := &User{
        name: "hezhixiong",
        uid:  int64(58741634),
    }

    ctx := context.WithValue(context.Background(), "name", user.name)
    ctx = context.WithValue(ctx, "uid", user.uid)
    ctx = context.WithValue(ctx, "user", user)

    go SafeFunc(test1, ctx)
    go SafeFunc(test2, ctx)
    go SafeFunc(test3, ctx)
    go SafeFunc(test4, ctx)

    for {
    }
}

func test1(ctx context.Context) {
    panic("test1")
}

func test2(ctx context.Context) {
    name := ctx.Value("name").(string)
    panic(name)
}

func test3(ctx context.Context) {
    name := ctx.Value("name").(string)
    uid := ctx.Value("uid").(int64)
    panic(fmt.Sprintln(name, uid))
}

func test4(ctx context.Context) {
    user := ctx.Value("user").(*User)
    panic(user)
}

// SafeFunc safe function call
func SafeFunc(f func(context.Context), ctx context.Context) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println(r)
        }
    }()
    f(ctx)
}

在生产中,通常会像这样扭曲输入和输出:

func test(in *input) (out *output) {
    // parse in
    // ... do something
    // build out
}

关于go - 重写goroutine函数并进行恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58741634/

相关文章:

pointers - 这段 Go 代码如何通过指针设置对象的值而不取消引用?

ssl - Artifactory jfrog cli 无法进行身份验证

go - 参数和从位置 [1] 传递的参数(不是位置 0)

linux - 调试器在带有 "Go"插件的 IntelliJ IDEA 中不起作用

go - 数据库和上下文错误太多

Go:属性存在但 Go 编译器说它不存在?

file-io - go 中的文件读取和校验和。方法之间的差异

go - 在其他操作系统上编译时,go 程序如何链接系统库?

go - 使用 []string 字段时出现无法比较的类型错误(Go lang)

go - 由结构包装的 sql.DB 无法在实例中调用方法