Catching panics in Golang

后端 未结 7 2024
自闭症患者
自闭症患者 2021-01-31 07:24

With the following code, if no file argument is given, a panic is thrown for line 9 panic: runtime error: index out of range as expected.

How can I \'catch\

7条回答
  •  猫巷女王i
    2021-01-31 07:51

    I had to catch panics in a test case. I got redirected here.

    func.go

    var errUnexpectedClose = errors.New("Unexpected Close")
    func closeTransaction(a bool) {
        if a == true {
            panic(errUnexpectedClose)
        }
    }
    

    func_test.go

    func TestExpectedPanic() {
        got := panicValue(func() { closeTransaction(true) })
        a, ok := got.(error)
        if a != errUnexpectedClose || !ok {
            t.Error("Expected ", errUnexpectedClose.Error())
        }
    }
    
    func panicValue(fn func()) (recovered interface{}) {
        defer func() {
            recovered = recover()
        }()
        fn()
        return
    }
    

    Used from https://github.com/golang/go/commit/e4f1d9cf2e948eb0f0bb91d7c253ab61dfff3a59 (ref from VonC)

提交回复
热议问题