登录
首页 >  Golang >  Go问答

重写goroutine函数并进行异常处理

来源:stackoverflow

时间:2024-02-23 23:27:17 444浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《重写goroutine函数并进行异常处理》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

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

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
}

今天关于《重写goroutine函数并进行异常处理》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>