Panics in libraries that spawn goroutines

Issue

What if an imported library spawns a goroutine that can panic? In this case, there is nothing a developer can do to stop the program from exiting.

Like in this code, calling a bad library with deferred recover does not help as the library is spawning a goroutine that panics, and it cannot be caught by the main’s recover.

Do I understand it correct that the only remedy is to be very careful when choosing dependencies for one’s project and hope that the authors do not do something similar?

package main

import (
    "fmt"
    "time"
)

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

    badLibrary()
}

func badLibrary() {
    go recklessFunction()
    time.Sleep(time.Second)
}

func recklessFunction() {
    panic("something went wrong")
}

Solution

You’re right, you can’t do anything about that. Neither can you if a dependency calls os.Exit() for example.

Launching goroutines as a library is often bad practice anyway, let the client (user of the library) choose if concurrent execution (a goroutine) is wanted, adding the go keyword is trivial. There are exceptions of course.

Answered By – icza

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.