I have a function which open db connection and return it. Or error, if something happened:
OpenDbConnection(connectionString string, logSql bool) (*gorm.DB, error)
In this function I am using logger:
logger := zap.NewExample().Sugar()
defer logger.Sync()
Method Sync()
returns error
and I am ignoring this error.
What is the best strategy in this case ?
I can rewrite my code to avoid linter error, but I am still ignore error:
logger := zap.NewExample().Sugar()
defer func() {
_ = logger.Sync()
}()
I can return error, but I am have correct db connection and I need to analyze this error in the calling function to understand what to do.
It's important to check for errors when closing a file, even in a deferred function. Running the program confirms that the file is closed after being written.
Go's built-in errors don't contain stack traces, nor do they support conventional try / catch methods to handle them. Instead, errors in Go are just values returned by functions, and they can be treated in much the same way as any other datatype - leading to a surprisingly lightweight and simple design.
In Go, we use defer, panic and recover statements to handle errors. We use defer to delay the execution of functions that might cause an error. The panic statement terminates the program immediately and recover is used to recover the message during panic.
In Go 1.13, though, Go added support for wrapping and unwrapping errors as part of the standard library by adding the errors. Unwrap function and the %w verb for the fmt. Errorf function. In this section, you'll update your program to use the %w verb to wrap errors with more information, and you'll then use errors.
You can name your returning error variable and initialize anywhere inside the function.
check this test code here
OpenDbConnection(connectionString string, logSql bool) (db *gorm.DB, err error) {
logger := zap.NewExample().Sugar()
defer func() {
err = logger.Sync()
}()
// some logic here
return db, err
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With