Handling errors in defer

前端 未结 1 1597
南笙
南笙 2021-01-05 16:04

I have a function which open db connection and return it. Or error, if something happened:

OpenDbConnection(connectionString string, logSql bool) (*gorm.DB,          


        
1条回答
  •  执笔经年
    2021-01-05 16:57

    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
    
    }
    

    0 讨论(0)
提交回复
热议问题