fabric-samples/off_chain_data/application-go/utils/utils.go
Stanislav Jakuschevskij 06c7445e91
Replace panic with error handling
Starting from the processor.Block.Process all methods now return errors
if something goes wrong with unpacking of the blocks and reading the
transactions. In each function where the error is being propagated back
to client it is wrapped in a message with the function name. This makes
it easier to track down the error and see the propagation chain. Finally
the error is logged to the terminal and the go routine shuts down
gracefully. The graceful shutdown executes all deferred functions which
close the context, the checkpointer and the gateway.

Before panics were used everywhere which was an issue because the
unpacking of the blocks happened in a go routine. When a panic happens
in a go routine only the deferred functions of the go routine are called
but not those of the client which lead to unexpected behavior.

The transact function is also executed in a go routine therefore the
same typo of error handling was implemented there.

Signed-off-by: Stanislav Jakuschevskij <stas@two-giants.com>
2025-02-24 13:14:48 +01:00

74 lines
1.6 KiB
Go

package utils
import (
"crypto/rand"
"errors"
"fmt"
"math/big"
"os"
)
// Pick a random element from an array.
func RandomElement(values []string) string {
result := values[RandomInt(len(values))]
return result
}
// Generate a random integer in the range 0 to max - 1.
func RandomInt(max int) int {
result, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
if err != nil {
panic(err)
}
return int(result.Int64())
}
// Pick a random element from an array, excluding the current value.
func DifferentElement(values []string, currentValue string) string {
candidateValues := []string{}
for _, v := range values {
if v != currentValue {
candidateValues = append(candidateValues, v)
}
}
return RandomElement(candidateValues)
}
// Return the value if it is defined; otherwise panics with an error message.
func AssertDefined[T any](value T, message string) (T, error) {
if any(value) == any(nil) {
var zeroValue T
return zeroValue, errors.New(message)
}
return value, nil
}
// Wrap a function call with a cache. On first call the wrapped function is invoked to
// obtain a result. Subsequent calls return the cached result.
func Cache[T any](f func() (T, error)) func() (T, error) {
var value T
var err error
var cached bool
return func() (T, error) {
if !cached {
value, err = f()
if err != nil {
var zeroValue T
return zeroValue, fmt.Errorf("in Cache: %w", err)
}
cached = true
}
return value, nil
}
}
func EnvOrDefault(key, defaultValue string) string {
result := os.Getenv(key)
if result == "" {
return defaultValue
}
return result
}