Senior
The service on production is not stable for more than 5 minutes. We managed to localize the problem — there is a certain function P() in an external library that panics with some probability. How to solve this problem? The library is open source, and the code can be viewed in the vendor.
sobes.tech AI
Answer from AI
If the function P() from an external library panics with some probability, and the library code is open, the following steps can be taken:
-
Wrap the call to function P() in a
recoverconstruct to catch the panic and prevent the entire service from crashing. -
Study the code of function P() in the vendor to understand the causes of the panic — it could be a logic error or incorrect usage.
-
If possible, fix the error in the library and rebuild it.
-
If fixing is not possible or takes time, you can write a wrapper around P() that safely calls the function and handles errors.
Example of a wrapper with recover in Go:
func safeP() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic caught: %v", r)
}
}()
P() // call to the problematic function
return nil
}
Thus, the service will not crash due to a panic, and errors can be logged and analyzed.