Golang coroutine cover exception to prevent flashback

Posted Jun 16, 20202 min read

Coroutine reports an error

If the coroutine does not cover the exception, there will be a flashback problem, but it is very difficult to deal with the need to cover every time you create various coroutines in large quantities. I am not very familiar with golang exception handling. I simply wrote one and don t know whether it is reliable

common

package logger

import(
    "fmt"
    "reflect"
    "runtime"
    "strings"

)

//Create a secure coroutine
func CreateSafeGo(call func(), errCall func(err interface{})) {
    go func() {
        defer SafeGoRecover(errCall)
        call()
    }()
}

func SafeGoRecover(errCall func(err interface{})) {
    if err := recover(); err != nil {
        Error("recover error:%v", err)
        if errCall != nil {
            errCall(err)
        }
    }
}

func getCaller() string {
    src := "No Caller"
    _, file, lineno, ok := runtime.Caller(2)
    var strim = "src/"
    //fix # Not every src in front, so you can get the current
    if ok {
        src = strings.Replace(fmt.Sprintf("%s:%d", stringTrim(file, strim), lineno), "%2e", ".", -1)
    }
    return src
}

//TODO Params
//Reflection realizes parameter recovery
func SafeGoWithParams(call interface{}, errCall func(err interface{}), params ...interface{}) {
    go func() {
        defer SafeGoRecover(errCall)
        funcValue := reflect.ValueOf(call)
        var paramsList []reflect.Value
        for _, v := range params {
            paramsList = append(paramsList, reflect.ValueOf(v))
        }
        funcValue.Call(paramsList)
    }()
}

test

package logger

import(
    "fmt"
    "testing"
    "time"

)

func TestCreateSafeGo(t *testing.T) {
    CreateSafeGo(func() {
        panic("1231")
    }, func(err interface{}) {
        Error("asdasd")

    })
    time.Sleep(time.Second)
}

func TestSafeGoRecover(t *testing.T) {
    go func() {
        defer SafeGoRecover(func(err interface{}) {
            Error("asdasd")
        })
        panic("1231")
    }()
    time.Sleep(time.Second)
}

func TestCreateSafeGoWithParams(t *testing.T) {
    SafeGoWithParams(func(aa int) {
        fmt.Println(aa)
    }, func(err interface{}) {

    }, 123)
    time.Sleep(time.Second)
}