Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors in defer

Tags:

go

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.

like image 559
ceth Avatar asked Aug 31 '19 17:08

ceth


People also ask

Should check returned error before deferring file close ()?

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.

How do you handle errors in go?

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.

Is defer executed on panic?

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.

How do you wrap errors in go?

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.


1 Answers

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

}
like image 105
Ahmed Hashem Avatar answered Sep 25 '22 10:09

Ahmed Hashem