Repository: snowflakedb/gosnowflake
Pull request #510 (2021-11-30 22:35:13)

SNOW-513580 Update Code Style
### Description
Update code to reflect https://github.com/golang/go/wiki/CodeReviewComments & https://go.dev/doc/effective_go.

### Checklist
- [ ] Code compiles correctly
- [ ] Run ``make fmt`` to fix inconsistent formats
- [ ] Run ``make lint`` to get lint errors and fix all of them
- [ ] Created tests which fail without the change (if possible)
- [ ] All tests passing
- [ ] Extended the README / documentation, if necessary



Patch:
diff --git a/azure_util.go b/azure_util.go
index 18838ff..3f84f5d 100644
--- a/azure_util.go
+++ b/azure_util.go
@@ -25,7 +25,7 @@ type azureLocation struct {
 	path          string
 }
 
-func (util *snowflakeAzureUtil) createClient(info *execResponseStageInfo, _ bool) cloudClient {
+func (util *snowflakeAzureUtil) createClient(info *execResponseStageInfo, _ bool) (cloudClient, error) {
 	sasToken := info.Creds.AzureSasToken
 	p := azblob.NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{
 		Retry: azblob.RetryOptions{
@@ -35,19 +35,25 @@ func (util *snowflakeAzureUtil) createClient(info *execResponseStageInfo, _ bool
 		},
 	})
 
-	u, _ := url.Parse(fmt.Sprintf("https://%s.%s/%s%s", info.StorageAccount, info.EndPoint, info.Path, sasToken))
+	u, err := url.Parse(fmt.Sprintf("https://%s.%s/%s%s", info.StorageAccount, info.EndPoint, info.Path, sasToken))
+	if err != nil {
+		return nil, err
+	}
 	containerURL := azblob.NewContainerURL(*u, p)
-	return &containerURL
+	return &containerURL, nil
 }
 
 // cloudUtil implementation
-func (util *snowflakeAzureUtil) getFileHeader(meta *fileMetadata, filename string) *fileHeader {
+func (util *snowflakeAzureUtil) getFileHeader(meta *fileMetadata, filename string) (*fileHeader, error) {
 	container, ok := meta.client.(*azblob.ContainerURL)
 	if !ok {
-		return nil
+		return nil, fmt.Errorf("failed to parse client to azblob.ContainerURL")
 	}
 
-	azureLoc := util.extractContainerNameAndPath(meta.stageInfo.Location)
+	azureLoc, err := util.extractContainerNameAndPath(meta.stageInfo.Location)
+	if err != nil {
+		return nil, err
+	}
 	path := azureLoc.path + strings.TrimLeft(filename, "/")
 	b := container.NewBlockBlobURL(path)
 	resp, err := b.GetProperties(context.Background(), azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
@@ -56,21 +62,21 @@ func (util *snowflakeAzureUtil) getFileHeader(meta *fileMetadata, filename strin
 		if errors.As(err, &se) {
 			if se.ServiceCode() == azblob.ServiceCodeBlobNotFound {
 				meta.resStatus = notFoundFile
-				return &fileHeader{}
+				return nil, fmt.Errorf("could not find file")
 			} else if se.Response().StatusCode == 403 {
 				meta.resStatus = renewToken
-				return nil
+				return nil, fmt.Errorf("received 403, attempting to renew")
 			}
 		}
 		meta.resStatus = errStatus
-		return nil
+		return nil, err
 	}
 
 	meta.resStatus = uploaded
 	metadata := resp.NewMetadata()
 	var encData encryptionData
 	if err = json.Unmarshal([]byte(metadata["encryptiondata"]), &encData); err != nil {
-		return nil
+		return nil, err
 	}
 	encryptionMetadata := encryptMetadata{
 		encData.WrappedContentKey.EncryptionKey,
@@ -82,7 +88,7 @@ func (util *snowflakeAzureUtil) getFileHeader(meta *fileMetadata, filename strin
 		metadata["sfcdigest"],
 		int64(len(metadata)),
 		&encryptionMetadata,
-	}
+	}, nil
 }
 
 // cloudUtil implementation
@@ -112,12 +118,18 @@ func (util *snowflakeAzureUtil) uploadFile(
 				"Java 5.3.0",
 			},
 		}
-		metadata, _ := json.Marshal(ed)
+		metadata, err := json.Marshal(ed)
+		if err != nil {
+			return err
+		}
 		azureMeta["encryptiondata"] = string(metadata)
 		azureMeta["matdesc"] = encryptMeta.matdesc
 	}
 
-	azureLoc := util.extractContainerNameAndPath(meta.stageInfo.Location)
+	azureLoc, err := util.extractContainerNameAndPath(meta.stageInfo.Location)
+	if err != nil {
+		return err
+	}
 	path := azureLoc.path + strings.TrimLeft(meta.dstFileName, "/")
 	azContainerURL, ok := meta.client.(*azblob.ContainerURL)
 	if !ok {
@@ -126,7 +138,6 @@ func (util *snowflakeAzureUtil) uploadFile(
 		}
 	}
 
-	var err error
 	blobURL := azContainerURL.NewBlockBlobURL(path)
 	if meta.srcStream != nil {
 		uploadSrc := meta.srcStream
@@ -138,9 +149,18 @@ func (util *snowflakeAzureUtil) uploadFile(
 			Metadata:   azureMeta,
 		})
 	} else {
-		f, _ := os.OpenFile(dataFile, os.O_RDONLY, os.ModePerm)
+		var f *os.File
+		f, err = os.OpenFile(dataFile, os.O_RDONLY, os.ModePerm)
+		if err != nil {
+			return err
+		}
 		defer f.Close()
-		fi, _ := f.Stat()
+
+		var fi os.FileInfo
+		fi, err = f.Stat()
+		if err != nil {
+			return err
+		}
 		_, err = azblob.UploadFileToBlockBlob(context.Background(), f, blobURL, azblob.UploadToBlockBlobOptions{
 			BlockSize:   fi.Size(),
 			Parallelism: uint16(maxConcurrency),
@@ -172,7 +192,10 @@ func (util *snowflakeAzureUtil) nativeDownloadFile(
 	meta *fileMetadata,
 	fullDstFileName string,
 	maxConcurrency int64) error {
-	azureLoc := util.extractContainerNameAndPath(meta.stageInfo.Location)
+	azureLoc, err := util.extractContainerNameAndPath(meta.stageInfo.Location)
+	if err != nil {
+		return err
+	}
 	path := azureLoc.path + strings.TrimLeft(meta.dstFileName, "/")
 	azContainerURL, ok := meta.client.(*azblob.ContainerURL)
 	if !ok {
@@ -196,8 +219,11 @@ func (util *snowflakeAzureUtil) nativeDownloadFile(
 	return nil
 }
 
-func (util *snowflakeAzureUtil) extractContainerNameAndPath(location string) *azureLocation {
-	stageLocation := expandUser(location)
+func (util *snowflakeAzureUtil) extractContainerNameAndPath(location string) (*azureLocation, error) {
+	stageLocation, err := expandUser(location)
+	if err != nil {
+		return nil, err
+	}
 	containerName := stageLocation
 	path := ""
 
@@ -208,7 +234,7 @@ func (util *snowflakeAzureUtil) extractContainerNameAndPath(location string) *az
 			path += "/"
 		}
 	}
-	return &azureLocation{containerName, path}
+	return &azureLocation{containerName, path}, nil
 }
 
 func (util *snowflakeAzureUtil) detectAzureTokenExpireError(resp *http.Response) bool {
diff --git a/bind_uploader.go b/bind_uploader.go
index f9cb8b2..1d9a242 100644
--- a/bind_uploader.go
+++ b/bind_uploader.go
@@ -30,11 +30,13 @@ type bindUploader struct {
 }
 
 func (bu *bindUploader) upload(bindings []driver.NamedValue) (*execResponse, error) {
-	bindingRows, _ := bu.buildRowsAsBytes(bindings)
+	bindingRows, err := bu.buildRowsAsBytes(bindings)
+	if err != nil {
+		return nil, err
+	}
 	startIdx, numBytes, rowNum := 0, 0, 0
 	bu.fileCount = 0
 	var data *execResponse
-	var err error
 	for rowNum < len(bindingRows) {
 		for numBytes < inputStreamBufferSize && rowNum < len(bindingRows) {
 			numBytes += len(bindingRows[rowNum])
@@ -233,7 +235,10 @@ func supportedArrayBind(nv *driver.NamedValue) bool {
 		return true
 	case reflect.TypeOf([]uint8{}):
 		// internal binding ts mode
-		val, _ := nv.Value.([]uint8)
+		val, ok := nv.Value.([]uint8)
+		if !ok {
+			return ok
+		}
 		if len(val) == 0 {
 			return true // for null binds
 		}
diff --git a/chunk_arrow.go b/chunk_arrow.go
index 4d7af56..f8abe47 100644
--- a/chunk_arrow.go
+++ b/chunk_arrow.go
@@ -5,9 +5,10 @@ package gosnowflake
 import (
 	"bytes"
 	"encoding/base64"
+	"io"
+
 	"github.com/apache/arrow/go/arrow/ipc"
 	"github.com/apache/arrow/go/arrow/memory"
-	"io"
 )
 
 type arrowResultChunk struct {
diff --git a/chunk_downloader.go b/chunk_downloader.go
index b75629b..9d8d9ed 100644
--- a/chunk_downloader.go
+++ b/chunk_downloader.go
@@ -8,8 +8,6 @@ import (
 	"context"
 	"encoding/json"
 	"fmt"
-	"github.com/apache/arrow/go/arrow/ipc"
-	"github.com/apache/arrow/go/arrow/memory"
 	"io"
 	"io/ioutil"
 	"math/rand"
@@ -19,6 +17,9 @@ import (
 	"strings"
 	"sync"
 	"time"
+
+	"github.com/apache/arrow/go/arrow/ipc"
+	"github.com/apache/arrow/go/arrow/memory"
 )
 
 type chunkDownloader interface {
@@ -565,14 +566,20 @@ func (f *httpStreamChunkFetcher) fetch(URL string, rows chan<- []*string) error
 		}
 	}
 
-	fullURL, _ := url.Parse(URL)
+	fullURL, err := url.Parse(URL)
+	if err != nil {
+		return err
+	}
 	res, err := newRetryHTTP(context.Background(), f.client, http.NewRequest, fullURL, f.headers, 0).execute()
 	if err != nil {
 		return err
 	}
 	defer res.Body.Close()
 	if res.StatusCode != http.StatusOK {
-		b, _ := ioutil.ReadAll(res.Body)
+		b, err := ioutil.ReadAll(res.Body)
+		if err != nil {
+			return err
+		}
 		return fmt.Errorf("status (%d): %s", res.StatusCode, string(b))
 	}
 	if err = copyChunkStream(res.Body, rows); err != nil {
diff --git a/cmd/externalbrowser/externalbrowser.go b/cmd/externalbrowser/externalbrowser.go
index f4ab9b1..e6e4f94 100644
--- a/cmd/externalbrowser/externalbrowser.go
+++ b/cmd/externalbrowser/externalbrowser.go
@@ -29,7 +29,10 @@ func getDSN() (string, *sf.Config, error) {
 	port := env("SNOWFLAKE_TEST_PORT", false)
 	protocol := env("SNOWFLAKE_TEST_PROTOCOL", false)
 
-	portStr, _ := strconv.Atoi(port)
+	portStr, err := strconv.Atoi(port)
+	if err != nil {
+		return "", nil, err
+	}
 	cfg := &sf.Config{
 		Authenticator: sf.AuthTypeExternalBrowser,
 		Account:       account,
diff --git a/cmd/keepalive/keepalive.go b/cmd/keepalive/keepalive.go
index 1899147..df9e9d7 100644
--- a/cmd/keepalive/keepalive.go
+++ b/cmd/keepalive/keepalive.go
@@ -10,9 +10,9 @@ import (
 	"log"
 	"os"
 	"strconv"
+	"time"
 
 	sf "github.com/snowflakedb/gosnowflake"
-	"time"
 )
 
 // getDSN constructs a DSN based on the test connection parameters
@@ -38,7 +38,10 @@ func getDSN() (string, *sf.Config, error) {
 	valueTrue := "true"
 	params["client_session_keep_alive"] = &valueTrue
 
-	portStr, _ := strconv.Atoi(port)
+	portStr, err := strconv.Atoi(port)
+	if err != nil {
+		return "", nil, err
+	}
 	cfg := &sf.Config{
 		Account:  account,
 		User:     user,
diff --git a/cmd/noconnpool/noconnpool.go b/cmd/noconnpool/noconnpool.go
index 973bce4..f369886 100644
--- a/cmd/noconnpool/noconnpool.go
+++ b/cmd/noconnpool/noconnpool.go
@@ -35,7 +35,10 @@ func getDSN() (string, *sf.Config, error) {
 	port := env("SNOWFLAKE_TEST_PORT", false)
 	protocol := env("SNOWFLAKE_TEST_PROTOCOL", false)
 
-	portStr, _ := strconv.Atoi(port)
+	portStr, err := strconv.Atoi(port)
+	if err != nil {
+		return "", nil, err
+	}
 	cfg := &sf.Config{
 		Account:  account,
 		User:     user,
diff --git a/cmd/select1/select1.go b/cmd/select1/select1.go
index 2ffccd7..57f379a 100644
--- a/cmd/select1/select1.go
+++ b/cmd/select1/select1.go
@@ -34,7 +34,10 @@ func getDSN() (string, *sf.Config, error) {
 	port := env("SNOWFLAKE_TEST_PORT", false)
 	protocol := env("SNOWFLAKE_TEST_PROTOCOL", false)
 
-	portStr, _ := strconv.Atoi(port)
+	portStr, err := strconv.Atoi(port)
+	if err != nil {
+		return "", nil, err
+	}
 	cfg := &sf.Config{
 		Account:  account,
 		User:     user,
diff --git a/cmd/selectmany/selectmany.go b/cmd/selectmany/selectmany.go
index 5c2737c..7689d56 100644
--- a/cmd/selectmany/selectmany.go
+++ b/cmd/selectmany/selectmany.go
@@ -41,7 +41,10 @@ func getDSN() (string, *sf.Config, error) {
 	port := env("SNOWFLAKE_TEST_PORT", false)
 	protocol := env("SNOWFLAKE_TEST_PROTOCOL", false)
 
-	portStr, _ := strconv.Atoi(port)
+	portStr, err := strconv.Atoi(port)
+	if err != nil {
+		return "", nil, err
+	}
 	cfg := &sf.Config{
 		Account:  account,
 		User:     user,
diff --git a/cmd/showparam/showparam.go b/cmd/showparam/showparam.go
index f9e6d15..a2ec355 100644
--- a/cmd/showparam/showparam.go
+++ b/cmd/showparam/showparam.go
@@ -32,7 +32,10 @@ func getDSN(params map[string]*string) (string, *sf.Config, error) {
 	port := env("SNOWFLAKE_TEST_PORT", false)
 	protocol := env("SNOWFLAKE_TEST_PROTOCOL", false)
 
-	portStr, _ := strconv.Atoi(port)
+	portStr, err := strconv.Atoi(port)
+	if err != nil {
+		return "", nil, err
+	}
 	cfg := &sf.Config{
 		Account:  account,
 		User:     user,
diff --git a/connection.go b/connection.go
index f06caba..c611c8e 100644
--- a/connection.go
+++ b/connection.go
@@ -528,7 +528,7 @@ func getAsync(
 	res *snowflakeResult,
 	rows *snowflakeRows,
 	cfg *Config,
-) {
+) error {
 	resType := getResultType(ctx)
 	var errChannel chan error
 	sfError := &SnowflakeError{
@@ -550,7 +550,7 @@ func getAsync(
 		sfError.Message = err.Error()
 		errChannel <- sfError
 		close(errChannel)
-		return
+		return err
 	}
 	if resp.Body != nil {
 		defer resp.Body.Close()
@@ -564,7 +564,7 @@ func getAsync(
 		sfError.Message = err.Error()
 		errChannel <- sfError
 		close(errChannel)
-		return
+		return err
 	}
 
 	sc := &snowflakeConn{rest: sr, cfg: cfg}
@@ -572,19 +572,22 @@ func getAsync(
 		if resType == execResultType {
 			res.insertID = -1
 			if isDml(respd.Data.StatementTypeID) {
-				res.affectedRows, _ = updateRows(respd.Data)
+				res.affectedRows, err = updateRows(respd.Data)
+				if err != nil {
+					return err
+				}
 			} else if isMultiStmt(&respd.Data) {
 				r, err := sc.handleMultiExec(ctx, respd.Data)
 				if err != nil {
 					res.errChannel <- err
 					close(errChannel)
-					return
+					return err
 				}
 				res.affectedRows, err = r.RowsAffected()
 				if err != nil {
 					res.errChannel <- err
 					close(errChannel)
-					return
+					return err
 				}
 			}
 			res.queryID = respd.Data.QueryID
@@ -593,11 +596,10 @@ func getAsync(
 			rows.sc = sc
 			rows.queryID = respd.Data.QueryID
 			if isMultiStmt(&respd.Data) {
-				err = sc.handleMultiQuery(ctx, respd.Data, rows)
-				if err != nil {
+				if err = sc.handleMultiQuery(ctx, respd.Data, rows); err != nil {
 					rows.errChannel <- err
 					close(errChannel)
-					return
+					return err
 				}
 			} else {
 				rows.addDownloader(populateChunkDownloader(ctx, sc, respd.Data))
@@ -622,6 +624,7 @@ func getAsync(
 			QueryID:  respd.Data.QueryID,
 		}
 	}
+	return nil
 }
 
 func buildSnowflakeConn(ctx context.Context, config Config) (*snowflakeConn, error) {
diff --git a/encrypt_util.go b/encrypt_util.go
index 1522bb7..2043a91 100644
--- a/encrypt_util.go
+++ b/encrypt_util.go
@@ -56,18 +56,23 @@ func encryptStream(
 	if chunkSize == 0 {
 		chunkSize = aes.BlockSize * 4 * 1024
 	}
-	decodedKey, _ := base64.StdEncoding.DecodeString(sfe.QueryStageMasterKey)
+	decodedKey, err := base64.StdEncoding.DecodeString(sfe.QueryStageMasterKey)
+	if err != nil {
+		return nil, err
+	}
 	keySize := len(decodedKey)
 
 	fileKey := getSecureRandom(keySize)
-	block, _ := aes.NewCipher(fileKey)
+	block, err := aes.NewCipher(fileKey)
+	if err != nil {
+		return nil, err
+	}
 	ivData := getSecureRandom(block.BlockSize())
 
 	mode := cipher.NewCBCEncrypter(block, ivData)
 	cipherText := make([]byte, chunkSize)
 
 	// encrypt file with CBC
-	var err error
 	for {
 		chunk := make([]byte, chunkSize)
 		n, err := src.Read(chunk)
@@ -97,15 +102,22 @@ func encryptStream(
 		strconv.Itoa(keySize * 8),
 	}
 
+	matDescUnicode, err := matdescToUnicode(matDesc)
+	if err != nil {
+		return nil, err
+	}
 	return &encryptMetadata{
 		base64.StdEncoding.EncodeToString(encryptedFileKey),
 		base64.StdEncoding.EncodeToString(ivData),
-		matdescToUnicode(matDesc),
+		matDescUnicode,
 	}, nil
 }
 
 func encryptECB(encrypted []byte, fileKey []byte, decodedKey []byte) error {
-	block, _ := aes.NewCipher(decodedKey)
+	block, err := aes.NewCipher(decodedKey)
+	if err != nil {
+		return err
+	}
 	if len(fileKey)%block.BlockSize() != 0 {
 		return fmt.Errorf("input not full of blocks")
 	}
@@ -121,7 +133,10 @@ func encryptECB(encrypted []byte, fileKey []byte, decodedKey []byte) error {
 }
 
 func decryptECB(decrypted []byte, keyBytes []byte, decodedKey []byte) error {
-	block, _ := aes.NewCipher(decodedKey)
+	block, err := aes.NewCipher(decodedKey)
+	if err != nil {
+		return err
+	}
 	if len(keyBytes)%block.BlockSize() != 0 {
 		return fmt.Errorf("input not full of blocks")
 	}
@@ -145,7 +160,10 @@ func encryptFile(
 	if chunkSize == 0 {
 		chunkSize = aes.BlockSize * 4 * 1024
 	}
-	tmpOutputFile, _ := ioutil.TempFile(tmpDir, baseName(filename)+"#")
+	tmpOutputFile, err := ioutil.TempFile(tmpDir, baseName(filename)+"#")
+	if err != nil {
+		return nil, "", err
+	}
 	infile, err := os.OpenFile(filename, os.O_CREATE|os.O_RDONLY, os.ModePerm)
 	if err != nil {
 		return nil, "", err
@@ -167,19 +185,31 @@ func decryptFile(
 	if chunkSize == 0 {
 		chunkSize = aes.BlockSize * 4 * 1024
 	}
-	decodedKey, _ := base64.StdEncoding.DecodeString(sfe.QueryStageMasterKey)
-	keyBytes, _ := base64.StdEncoding.DecodeString(metadata.key) // encrypted file key
-	ivBytes, _ := base64.StdEncoding.DecodeString(metadata.iv)
+	decodedKey, err := base64.StdEncoding.DecodeString(sfe.QueryStageMasterKey)
+	if err != nil {
+		return "", err
+	}
+	keyBytes, err := base64.StdEncoding.DecodeString(metadata.key) // encrypted file key
+	if err != nil {
+		return "", err
+	}
+	ivBytes, err := base64.StdEncoding.DecodeString(metadata.iv)
+	if err != nil {
+		return "", err
+	}
 
 	// decrypt file key
 	decryptedKey := make([]byte, len(keyBytes))
-	if err := decryptECB(decryptedKey, keyBytes, decodedKey); err != nil {
+	if err = decryptECB(decryptedKey, keyBytes, decodedKey); err != nil {
 		return "", err
 	}
 	decryptedKey = paddingTrim(decryptedKey)
 
 	// decrypt file
-	block, _ := aes.NewCipher(decryptedKey)
+	block, err := aes.NewCipher(decryptedKey)
+	if err != nil {
+		return "", err
+	}
 	mode := cipher.NewCBCDecrypter(block, ivBytes)
 
 	tmpOutputFile, err := ioutil.TempFile(tmpDir, baseName(filename)+"#")
@@ -222,9 +252,12 @@ type materialDescriptor struct {
 	KeySize string `json:"keySize"`
 }
 
-func matdescToUnicode(matdesc materialDescriptor) string {
-	s, _ := json.Marshal(&matdesc)
-	return string(s)
+func matdescToUnicode(matdesc materialDescriptor) (string, error) {
+	s, err := json.Marshal(&matdesc)
+	if err != nil {
+		return "", err
+	}
+	return string(s), nil
 }
 
 func getSecureRandom(byteLength int) []byte {
diff --git a/file_transfer_agent.go b/file_transfer_agent.go
index 39208e4..40e6aef 100644
--- a/file_transfer_agent.go
+++ b/file_transfer_agent.go
@@ -201,6 +201,7 @@ func (sfa *snowflakeFileTransferAgent) execute() error {
 }
 
 func (sfa *snowflakeFileTransferAgent) parseCommand() error {
+	var err error
 	if sfa.data.Command != "" {
 		sfa.commandType = commandType(sfa.data.Command)
 	} else {
@@ -222,7 +223,10 @@ func (sfa *snowflakeFileTransferAgent) parseCommand() error {
 		if sfa.sourceStream != nil {
 			sfa.srcFiles = sfa.srcLocations // streaming PUT
 		} else {
-			sfa.srcFiles = sfa.expandFilenames(sfa.srcLocations)
+			sfa.srcFiles, err = sfa.expandFilenames(sfa.srcLocations)
+			if err != nil {
+				return err
+			}
 		}
 		sfa.autoCompress = sfa.data.AutoCompress
 		sfa.srcCompression = strings.ToLower(sfa.data.SourceCompression)
@@ -244,8 +248,11 @@ func (sfa *snowflakeFileTransferAgent) parseCommand() error {
 			}).exceptionTelemetry(sfa.sc)
 		}
 
-		sfa.localLocation = expandUser(sfa.data.LocalLocation)
-		if fi, _ := os.Stat(sfa.localLocation); !fi.IsDir() {
+		sfa.localLocation, err = expandUser(sfa.data.LocalLocation)
+		if err != nil {
+			return err
+		}
+		if fi, err := os.Stat(sfa.localLocation); !fi.IsDir() || err != nil {
 			return (&SnowflakeError{
 				Number:   ErrLocalPathNotDirectory,
 				SQLState: sfa.data.SQLState,
@@ -297,13 +304,20 @@ func (sfa *snowflakeFileTransferAgent) initEncryptionMaterial() {
 	}
 }
 
-func (sfa *snowflakeFileTransferAgent) expandFilenames(locations []string) []string {
+func (sfa *snowflakeFileTransferAgent) expandFilenames(locations []string) ([]string, error) {
 	canonicalLocations := make([]string, 0)
 	for _, fileName := range locations {
 		if sfa.commandType == uploadCommand {
-			fileName = expandUser(fileName)
+			var err error
+			fileName, err = expandUser(fileName)
+			if err != nil {
+				return []string{}, err
+			}
 			if !filepath.IsAbs(fileName) {
-				cwd, _ := getDirectory()
+				cwd, err := getDirectory()
+				if err != nil {
+					return []string{}, err
+				}
 				fileName = filepath.Join(cwd, fileName)
 			}
 			if isWindows && len(fileName) > 2 && fileName[0] == '/' && fileName[2] == ':' {
@@ -313,14 +327,14 @@ func (sfa *snowflakeFileTransferAgent) expandFilenames(locations []string) []str
 			}
 			files, err := filepath.Glob(fileName)
 			if err != nil {
-				return []string{}
+				return []string{}, err
 			}
 			canonicalLocations = append(canonicalLocations, files...)
 		} else {
 			canonicalLocations = append(canonicalLocations, fileName)
 		}
 	}
-	return canonicalLocations
+	return canonicalLocations, nil
 }
 
 func (sfa *snowflakeFileTransferAgent) initFileMetadata() error {
@@ -446,12 +460,19 @@ func (sfa *snowflakeFileTransferAgent) processFileCompressionType() error {
 			currentFileCompressionType = lookupByExtension(filepath.Ext(fileName))
 			if currentFileCompressionType == nil {
 				var mtype *mimetype.MIME
+				var err error
 				if meta.srcStream != nil {
 					r := getReaderFromBuffer(&meta.srcStream)
-					mtype, _ = mimetype.DetectReader(r)
+					mtype, err = mimetype.DetectReader(r)
+					if err != nil {
+						return err
+					}
 					ioutil.ReadAll(r) // flush out tee buffer
 				} else {
-					mtype, _ = mimetype.DetectFile(fileName)
+					mtype, err = mimetype.DetectFile(fileName)
+					if err != nil {
+						return err
+					}
 				}
 				currentFileCompressionType = lookupByExtension(mtype.Extension())
 			}
@@ -513,7 +534,10 @@ func (sfa *snowflakeFileTransferAgent) updateFileMetadataWithPresignedURL() erro
 				}
 				headers := getHeaders()
 				headers[httpHeaderAccept] = headerContentTypeApplicationJSON
-				jsonBody, _ := json.Marshal(req)
+				jsonBody, err := json.Marshal(req)
+				if err != nil {
+					return err
+				}
 				data, err := sfa.sc.rest.FuncPostQuery(
 					sfa.sc.ctx,
 					sfa.sc.rest,
@@ -531,14 +555,21 @@ func (sfa *snowflakeFileTransferAgent) updateFileMetadataWithPresignedURL() erro
 					meta.stageInfo = &data.Data.StageInfo
 					meta.presignedURL = nil
 					if meta.stageInfo.PresignedURL != "" {
-						meta.presignedURL, _ = url.Parse(meta.stageInfo.PresignedURL)
+						meta.presignedURL, err = url.Parse(meta.stageInfo.PresignedURL)
+						if err != nil {
+							return err
+						}
 					}
 				}
 			}
 		} else if sfa.commandType == downloadCommand {
 			for i, meta := range sfa.fileMetadata {
 				if len(sfa.presignedURLs) > 0 {
-					meta.presignedURL, _ = url.Parse(sfa.presignedURLs[i])
+					var err error
+					meta.presignedURL, err = url.Parse(sfa.presignedURLs[i])
+					if err != nil {
+						return err
+					}
 				} else {
 					meta.presignedURL = nil
 				}
@@ -558,8 +589,15 @@ func (sfa *snowflakeFileTransferAgent) updateFileMetadataWithPresignedURL() erro
 func (sfa *snowflakeFileTransferAgent) transferAccelerateConfig() error {
 	if sfa.stageLocationType == s3Client {
 		s3Util := new(snowflakeS3Util)
-		s3Loc := s3Util.extractBucketNameAndPath(sfa.stageInfo.Location)
-		client, ok := s3Util.createClient(sfa.stageInfo, false).(*s3.Client)
+		s3Loc, err := s3Util.extractBucketNameAndPath(sfa.stageInfo.Location)
+		if err != nil {
+			return err
+		}
+		s3Cli, err := s3Util.createClient(sfa.stageInfo, false)
+		if err != nil {
+			return err
+		}
+		client, ok := s3Cli.(*s3.Client)
 		if !ok {
 			return (&SnowflakeError{
 				SQLState: sfa.data.SQLState,
@@ -628,8 +666,11 @@ func (sfa *snowflakeFileTransferAgent) getLocalFilePathFromCommand(command strin
 func (sfa *snowflakeFileTransferAgent) upload(
 	largeFileMetadata []*fileMetadata,
 	smallFileMetadata []*fileMetadata) error {
-	client := sfa.getStorageClient(sfa.stageLocationType).
+	client, err := sfa.getStorageClient(sfa.stageLocationType).
 		createClient(sfa.stageInfo, sfa.useAccelerateEndpoint)
+	if err != nil {
+		return err
+	}
 	for _, meta := range smallFileMetadata {
 		meta.client = client
 	}
@@ -638,12 +679,12 @@ func (sfa *snowflakeFileTransferAgent) upload(
 	}
 
 	if len(smallFileMetadata) > 0 {
-		if err := sfa.uploadFilesParallel(smallFileMetadata); err != nil {
+		if err = sfa.uploadFilesParallel(smallFileMetadata); err != nil {
 			return err
 		}
 	}
 	if len(largeFileMetadata) > 0 {
-		if err := sfa.uploadFilesSequential(largeFileMetadata); err != nil {
+		if err = sfa.uploadFilesSequential(largeFileMetadata); err != nil {
 			return err
 		}
 	}
@@ -653,8 +694,11 @@ func (sfa *snowflakeFileTransferAgent) upload(
 func (sfa *snowflakeFileTransferAgent) download(
 	largeFileMetadata []*fileMetadata,
 	smallFileMetadata []*fileMetadata) error {
-	client := sfa.getStorageClient(sfa.stageLocationType).
+	client, err := sfa.getStorageClient(sfa.stageLocationType).
 		createClient(sfa.stageInfo, sfa.useAccelerateEndpoint)
+	if err != nil {
+		return err
+	}
 	for _, meta := range smallFileMetadata {
 		meta.client = client
 	}
@@ -664,13 +708,13 @@ func (sfa *snowflakeFileTransferAgent) download(
 
 	if len(smallFileMetadata) > 0 {
 		logger.WithContext(sfa.sc.ctx).Infof("downloading %v small files", len(smallFileMetadata))
-		if err := sfa.downloadFilesParallel(smallFileMetadata); err != nil {
+		if err = sfa.downloadFilesParallel(smallFileMetadata); err != nil {
 			return err
 		}
 	}
 	if len(largeFileMetadata) > 0 {
 		logger.WithContext(sfa.sc.ctx).Infof("downloading %v large files", len(largeFileMetadata))
-		if err := sfa.downloadFilesSequential(largeFileMetadata); err != nil {
+		if err = sfa.downloadFilesSequential(largeFileMetadata); err != nil {
 			return err
 		}
 	}
@@ -718,7 +762,10 @@ func (sfa *snowflakeFileTransferAgent) uploadFilesParallel(fileMetas []*fileMeta
 			}
 
 			if needRenewToken {
-				client := sfa.renewExpiredClient()
+				client, err := sfa.renewExpiredClient()
+				if err != nil {
+					return err
+				}
 				for _, result := range retryMeta {
 					result.client = client
 				}
@@ -755,7 +802,10 @@ func (sfa *snowflakeFileTransferAgent) uploadFilesSequential(fileMetas []*fileMe
 		}
 
 		if res.resStatus == renewToken {
-			client := sfa.renewExpiredClient()
+			client, err := sfa.renewExpiredClient()
+			if err != nil {
+				return err
+			}
 			for i := idx; i < fileMetaLen; i++ {
 				fileMetas[i].client = client
 			}
@@ -776,20 +826,25 @@ func (sfa *snowflakeFileTransferAgent) uploadFilesSequential(fileMetas []*fileMe
 
 func (sfa *snowflakeFileTransferAgent) uploadOneFile(meta *fileMetadata) (*fileMetadata, error) {
 	meta.realSrcFileName = meta.srcFileName
-	tmpDir, _ := ioutil.TempDir("", "")
+	tmpDir, err := ioutil.TempDir("", "")
+	if err != nil {
+		return nil, err
+	}
 	meta.tmpDir = tmpDir
 	defer os.RemoveAll(tmpDir) // cleanup
 
 	fileUtil := new(snowflakeFileUtil)
 	if meta.requireCompress {
 		if meta.srcStream != nil {
-			meta.realSrcStream, _ = fileUtil.compressFileWithGzipFromStream(&meta.srcStream)
+			meta.realSrcStream, _, err = fileUtil.compressFileWithGzipFromStream(&meta.srcStream)
 		} else {
-			meta.realSrcFileName, _ = fileUtil.compressFileWithGzip(meta.srcFileName, tmpDir)
+			meta.realSrcFileName, _, err = fileUtil.compressFileWithGzip(meta.srcFileName, tmpDir)
+		}
+		if err != nil {
+			return nil, err
 		}
 	}
 
-	var err error
 	if meta.srcStream != nil {
 		if meta.realSrcStream != nil {
 			meta.sha256Digest, meta.uploadSize = fileUtil.getDigestAndSizeForStream(&meta.realSrcStream)
@@ -855,7 +910,10 @@ func (sfa *snowflakeFileTransferAgent) downloadFilesParallel(fileMetas []*fileMe
 			}
 
 			if needRenewToken {
-				client := sfa.renewExpiredClient()
+				client, err := sfa.renewExpiredClient()
+				if err != nil {
+					return err
+				}
 				for _, result := range retryMeta {
 					result.client = client
 				}
@@ -892,7 +950,10 @@ func (sfa *snowflakeFileTransferAgent) downloadFilesSequential(fileMetas []*file
 		}
 
 		if res.resStatus == renewToken {
-			client := sfa.renewExpiredClient()
+			client, err := sfa.renewExpiredClient()
+			if err != nil {
+				return err
+			}
 			for i := idx; i < fileMetaLen; i++ {
 				fileMetas[i].client = client
 			}
@@ -912,11 +973,14 @@ func (sfa *snowflakeFileTransferAgent) downloadFilesSequential(fileMetas []*file
 }
 
 func (sfa *snowflakeFileTransferAgent) downloadOneFile(meta *fileMetadata) (*fileMetadata, error) {
-	tmpDir, _ := ioutil.TempDir("", "")
+	tmpDir, err := ioutil.TempDir("", "")
+	if err != nil {
+		return nil, err
+	}
 	meta.tmpDir = tmpDir
 	defer os.RemoveAll(tmpDir) // cleanup
 	client := sfa.getStorageClient(sfa.stageLocationType)
-	if err := client.downloadOneFile(meta); err != nil {
+	if err = client.downloadOneFile(meta); err != nil {
 		meta.dstFileSize = -1
 		if !meta.resStatus.isSet() {
 			meta.resStatus = errStatus
@@ -936,7 +1000,7 @@ func (sfa *snowflakeFileTransferAgent) getStorageClient(stageLocationType cloudT
 	return nil
 }
 
-func (sfa *snowflakeFileTransferAgent) renewExpiredClient() cloudClient {
+func (sfa *snowflakeFileTransferAgent) renewExpiredClient() (cloudClient, error) {
 	data, err := sfa.sc.exec(
 		sfa.sc.ctx,
 		sfa.command,
@@ -945,7 +1009,7 @@ func (sfa *snowflakeFileTransferAgent) renewExpiredClient() cloudClient {
 		false,
 		[]driver.NamedValue{})
 	if err != nil {
-		return nil
+		return nil, err
 	}
 	storageClient := sfa.getStorageClient(sfa.stageLocationType)
 	return storageClient.createClient(&data.Data.StageInfo, sfa.useAccelerateEndpoint)
diff --git a/file_util.go b/file_util.go
index a507995..65a46e1 100644
--- a/file_util.go
+++ b/file_util.go
@@ -19,29 +19,41 @@ import (
 type snowflakeFileUtil struct {
 }
 
-func (util *snowflakeFileUtil) compressFileWithGzipFromStream(srcStream **bytes.Buffer) (*bytes.Buffer, int) {
+func (util *snowflakeFileUtil) compressFileWithGzipFromStream(srcStream **bytes.Buffer) (*bytes.Buffer, int, error) {
 	r := getReaderFromBuffer(srcStream)
-	buf, _ := ioutil.ReadAll(r)
+	buf, err := ioutil.ReadAll(r)
+	if err != nil {
+		return nil, -1, err
+	}
 	var c bytes.Buffer
 	w := gzip.NewWriter(&c)
 	w.Write(buf) // write buf to gzip writer
 	w.Close()
-	return &c, c.Len()
+	return &c, c.Len(), nil
 }
 
-func (util *snowflakeFileUtil) compressFileWithGzip(fileName string, tmpDir string) (string, int64) {
+func (util *snowflakeFileUtil) compressFileWithGzip(fileName string, tmpDir string) (string, int64, error) {
 	basename := baseName(fileName)
 	gzipFileName := filepath.Join(tmpDir, basename+"_c.gz")
 
-	fr, _ := os.OpenFile(fileName, os.O_RDONLY, os.ModePerm)
+	fr, err := os.OpenFile(fileName, os.O_RDONLY, os.ModePerm)
+	if err != nil {
+		return "", -1, err
+	}
 	defer fr.Close()
-	fw, _ := os.OpenFile(gzipFileName, os.O_WRONLY|os.O_CREATE, os.ModePerm)
+	fw, err := os.OpenFile(gzipFileName, os.O_WRONLY|os.O_CREATE, os.ModePerm)
+	if err != nil {
+		return "", -1, err
+	}
 	gzw := gzip.NewWriter(fw)
 	defer gzw.Close()
 	io.Copy(gzw, fr)
 
-	stat, _ := os.Stat(gzipFileName)
-	return gzipFileName, stat.Size()
+	stat, err := os.Stat(gzipFileName)
+	if err != nil {
+		return "", -1, err
+	}
+	return gzipFileName, stat.Size(), nil
 }
 
 func (util *snowflakeFileUtil) getDigestAndSize(src **bytes.Buffer) (string, int64) {
@@ -157,15 +169,18 @@ func baseName(path string) string {
 }
 
 // expandUser returns the argument with an initial component of ~
-func expandUser(path string) string {
-	usr, _ := usr.Current()
+func expandUser(path string) (string, error) {
+	usr, err := usr.Current()
+	if err != nil {
+		return "", err
+	}
 	dir := usr.HomeDir
 	if path == "~" {
 		path = dir
 	} else if strings.HasPrefix(path, "~/") {
 		path = filepath.Join(dir, path[2:])
 	}
-	return path
+	return path, nil
 }
 
 // getDirectory retrieves the current working directory
diff --git a/gcs_util.go b/gcs_util.go
index e9de6f5..41b6b91 100644
--- a/gcs_util.go
+++ b/gcs_util.go
@@ -29,26 +29,29 @@ type gcsLocation struct {
 	path       string
 }
 
-func (util *snowflakeGcsUtil) createClient(info *execResponseStageInfo, _ bool) cloudClient {
+func (util *snowflakeGcsUtil) createClient(info *execResponseStageInfo, _ bool) (cloudClient, error) {
 	if info.Creds.GcsAccessToken != "" {
-		return info.Creds.GcsAccessToken
+		return info.Creds.GcsAccessToken, nil
 	}
-	return ""
+	return "", nil
 }
 
 // cloudUtil implementation
-func (util *snowflakeGcsUtil) getFileHeader(meta *fileMetadata, filename string) *fileHeader {
+func (util *snowflakeGcsUtil) getFileHeader(meta *fileMetadata, filename string) (*fileHeader, error) {
 	if meta.resStatus == uploaded || meta.resStatus == downloaded {
 		return &fileHeader{
 			digest:             meta.gcsFileHeaderDigest,
 			contentLength:      meta.gcsFileHeaderContentLength,
 			encryptionMetadata: meta.gcsFileHeaderEncryptionMeta,
-		}
+		}, nil
 	}
 	if meta.presignedURL != nil {
 		meta.resStatus = notFoundFile
 	} else {
-		URL := util.generateFileURL(meta.stageInfo.Location, strings.TrimLeft(filename, "/"))
+		URL, err := util.generateFileURL(meta.stageInfo.Location, strings.TrimLeft(filename, "/"))
+		if err != nil {
+			return nil, err
+		}
 		accessToken := meta.client.(string)
 		gcsHeaders := map[string]string{
 			"Authorization": "Bearer " + accessToken,
@@ -56,18 +59,21 @@ func (util *snowflakeGcsUtil) getFileHeader(meta *fileMetadata, filename string)
 
 		req, err := http.NewRequest("HEAD", URL.String(), nil)
 		if err != nil {
-			return nil
+			return nil, err
 		}
 		for k, v := range gcsHeaders {
 			req.Header.Add(k, v)
 		}
 		client := &http.Client{}
-		resp, _ := client.Do(req)
+		resp, err := client.Do(req)
+		if err != nil {
+			return nil, err
+		}
 		if resp.StatusCode != http.StatusOK {
 			if resp.StatusCode == 403 || resp.StatusCode == 408 || resp.StatusCode == 429 || resp.StatusCode == 500 || resp.StatusCode == 503 {
 				meta.lastError = fmt.Errorf(resp.Status)
 				meta.resStatus = needRetry
-				return nil
+				return nil, meta.lastError
 			}
 			if resp.StatusCode == 404 {
 				meta.resStatus = notFoundFile
@@ -77,11 +83,14 @@ func (util *snowflakeGcsUtil) getFileHeader(meta *fileMetadata, filename string)
 			}
 			meta.lastError = fmt.Errorf(resp.Status)
 			meta.resStatus = errStatus
-			return nil
+			return nil, meta.lastError
 		}
 
 		digest := resp.Header.Get(gcsMetadataSfcDigest)
-		contentLength, _ := strconv.Atoi(resp.Header.Get("content-length"))
+		contentLength, err := strconv.Atoi(resp.Header.Get("content-length"))
+		if err != nil {
+			return nil, err
+		}
 		var encryptionMeta *encryptMetadata
 		if resp.Header.Get(gcsMetadataEncryptionDataProp) != "" {
 			var encryptData *encryptionData
@@ -101,18 +110,27 @@ func (util *snowflakeGcsUtil) getFileHeader(meta *fileMetadata, filename string)
 			digest:             digest,
 			contentLength:      int64(contentLength),
 			encryptionMetadata: encryptionMeta,
-		}
+		}, nil
 	}
-	return nil
+	return nil, nil
 }
 
 // cloudUtil implementation
-func (util *snowflakeGcsUtil) uploadFile(dataFile string, meta *fileMetadata, encryptMeta *encryptMetadata, maxConcurrency int, multiPartThreshold int64) error {
+func (util *snowflakeGcsUtil) uploadFile(
+	dataFile string,
+	meta *fileMetadata,
+	encryptMeta *encryptMetadata,
+	maxConcurrency int,
+	multiPartThreshold int64) error {
 	uploadURL := meta.presignedURL
 	var accessToken string
+	var err error
 
 	if uploadURL == nil {
-		uploadURL = util.generateFileURL(meta.stageInfo.Location, strings.TrimLeft(meta.dstFileName, "/"))
+		_, err = util.generateFileURL(meta.stageInfo.Location, strings.TrimLeft(meta.dstFileName, "/"))
+		if err != nil {
+			return err
+		}
 		accessToken = meta.client.(string)
 	}
 
@@ -149,7 +167,10 @@ func (util *snowflakeGcsUtil) uploadFile(dataFile string, meta *fileMetadata, en
 				"Java 5.3.0",
 			},
 		}
-		b, _ := json.Marshal(&encryptData)
+		b, err := json.Marshal(&encryptData)
+		if err != nil {
+			return err
+		}
 		gcsHeaders[gcsMetadataEncryptionDataProp] = string(b)
 		gcsHeaders[gcsMetadataMatdescKey] = encryptMeta.matdesc
 	}
@@ -161,7 +182,10 @@ func (util *snowflakeGcsUtil) uploadFile(dataFile string, meta *fileMetadata, en
 			uploadSrc = meta.realSrcStream
 		}
 	} else {
-		uploadSrc, _ = os.OpenFile(dataFile, os.O_RDONLY, os.ModePerm)
+		uploadSrc, err = os.OpenFile(dataFile, os.O_RDONLY, os.ModePerm)
+		if err != nil {
+			return err
+		}
 	}
 
 	req, err := http.NewRequest("PUT", uploadURL.String(), uploadSrc)
@@ -172,7 +196,10 @@ func (util *snowflakeGcsUtil) uploadFile(dataFile string, meta *fileMetadata, en
 		req.Header.Add(k, v)
 	}
 	client := &http.Client{}
-	resp, _ := client.Do(req)
+	resp, err := client.Do(req)
+	if err != nil {
+		return err
+	}
 	if resp.StatusCode != http.StatusOK {
 		meta.lastError = fmt.Errorf(resp.Status)
 		if resp.StatusCode == 403 || resp.StatusCode == 408 || resp.StatusCode == 429 || resp.StatusCode == 500 || resp.StatusCode == 503 {
@@ -216,10 +243,14 @@ func (util *snowflakeGcsUtil) nativeDownloadFile(
 	maxConcurrency int64) error {
 	downloadURL := meta.presignedURL
 	var accessToken string
+	var err error
 	gcsHeaders := make(map[string]string)
 
 	if downloadURL == nil {
-		downloadURL = util.generateFileURL(meta.stageInfo.Location, strings.TrimLeft(meta.dstFileName, "/"))
+		downloadURL, err = util.generateFileURL(meta.stageInfo.Location, strings.TrimLeft(meta.dstFileName, "/"))
+		if err != nil {
+			return err
+		}
 		accessToken = meta.client.(string)
 		if accessToken != "" {
 			gcsHeaders["Authorization"] = "Bearer " + accessToken
@@ -234,7 +265,10 @@ func (util *snowflakeGcsUtil) nativeDownloadFile(
 		req.Header.Add(k, v)
 	}
 	client := &http.Client{}
-	resp, _ := client.Do(req)
+	resp, err := client.Do(req)
+	if err != nil {
+		return err
+	}
 	if resp.StatusCode != http.StatusOK {
 		meta.lastError = fmt.Errorf(resp.Status)
 		if resp.StatusCode == 403 || resp.StatusCode == 408 || resp.StatusCode == 429 || resp.StatusCode == 500 || resp.StatusCode == 503 {
@@ -302,11 +336,14 @@ func (util *snowflakeGcsUtil) extractBucketNameAndPath(location string) *gcsLoca
 	return &gcsLocation{containerName, path}
 }
 
-func (util *snowflakeGcsUtil) generateFileURL(stageLocation string, filename string) *url.URL {
+func (util *snowflakeGcsUtil) generateFileURL(stageLocation string, filename string) (*url.URL, error) {
 	gcsLoc := util.extractBucketNameAndPath(stageLocation)
 	fullFilePath := gcsLoc.path + filename
-	URL, _ := url.Parse("https://storage.googleapis.com/" + gcsLoc.bucketName + "/" + url.QueryEscape(fullFilePath))
-	return URL
+	URL, err := url.Parse("https://storage.googleapis.com/" + gcsLoc.bucketName + "/" + url.QueryEscape(fullFilePath))
+	if err != nil {
+		return nil, err
+	}
+	return URL, nil
 }
 
 func (util *snowflakeGcsUtil) isTokenExpired(resp *http.Response) bool {
diff --git a/local_util.go b/local_util.go
index 691d8aa..08c7b7c 100644
--- a/local_util.go
+++ b/local_util.go
@@ -16,8 +16,8 @@ import (
 type localUtil struct {
 }
 
-func (util *localUtil) createClient(_ *execResponseStageInfo, _ bool) cloudClient {
-	return nil
+func (util *localUtil) createClient(_ *execResponseStageInfo, _ bool) (cloudClient, error) {
+	return nil, nil
 }
 
 func (util *localUtil) uploadOneFileWithRetry(meta *fileMetadata) error {
@@ -29,19 +29,26 @@ func (util *localUtil) uploadOneFileWithRetry(meta *fileMetadata) error {
 		}
 		frd = bufio.NewReader(b)
 	} else {
-		f, _ := os.Open(meta.realSrcFileName)
+		f, err := os.Open(meta.realSrcFileName)
+		if err != nil {
+			return err
+		}
 		defer f.Close()
 		frd = bufio.NewReader(f)
 	}
 
+	user, err := expandUser(meta.stageInfo.Location)
+	if err != nil {
+		return err
+	}
 	if !meta.overwrite {
-		if _, err := os.Stat(filepath.Join(expandUser(meta.stageInfo.Location), meta.dstFileName)); err == nil {
+		if _, err := os.Stat(filepath.Join(user, meta.dstFileName)); err == nil {
 			meta.dstFileSize = 0
 			meta.resStatus = skipped
 			return nil
 		}
 	}
-	output, err := os.OpenFile(filepath.Join(expandUser(meta.stageInfo.Location), meta.dstFileName), os.O_CREATE|os.O_WRONLY, os.ModePerm)
+	output, err := os.OpenFile(filepath.Join(user, meta.dstFileName), os.O_CREATE|os.O_WRONLY, os.ModePerm)
 	if err != nil {
 		return err
 	}
@@ -70,8 +77,16 @@ func (util *localUtil) downloadOneFile(meta *fileMetadata) error {
 	if strings.HasPrefix(meta.srcFileName, fmt.Sprintf("%b", os.PathSeparator)) {
 		srcFileName = srcFileName[1:]
 	}
-	fullSrcFileName := path.Join(expandUser(meta.stageInfo.Location), srcFileName)
-	fullDstFileName := path.Join(expandUser(meta.localLocation), baseName(meta.dstFileName))
+	user, err := expandUser(meta.stageInfo.Location)
+	if err != nil {
+		return err
+	}
+	fullSrcFileName := path.Join(user, srcFileName)
+	user, err = expandUser(meta.localLocation)
+	if err != nil {
+		return err
+	}
+	fullDstFileName := path.Join(user, baseName(meta.dstFileName))
 	baseDir, err := getDirectory()
 	if err != nil {
 		return err
diff --git a/restful.go b/restful.go
index 81f040d..c0b707b 100644
--- a/restful.go
+++ b/restful.go
@@ -434,7 +434,10 @@ func getCancelRetry(ctx context.Context) int {
 	if val == nil {
 		return 5
 	}
-	cnt, _ := val.(int)
+	cnt, ok := val.(int)
+	if !ok {
+		return -1
+	}
 	return cnt
 }
 
@@ -472,8 +475,7 @@ func cancelQuery(ctx context.Context, sr *snowflakeRestful, requestID uuid.UUID,
 		}
 		ctxRetry := getCancelRetry(ctx)
 		if !respd.Success && respd.Code == sessionExpiredCode {
-			err := sr.FuncRenewSession(ctx, sr, timeout)
-			if err != nil {
+			if err = sr.FuncRenewSession(ctx, sr, timeout); err != nil {
 				return err
 			}
 			return sr.FuncCancelQuery(ctx, sr, requestID, timeout)
@@ -512,6 +514,9 @@ func getQueryIDChan(ctx context.Context) chan<- string {
 	if v == nil {
 		return nil
 	}
-	c, _ := v.(chan<- string)
+	c, ok := v.(chan<- string)
+	if !ok {
+		return nil
+	}
 	return c
 }
diff --git a/retry.go b/retry.go
index 1c42801..16c38b3 100644
--- a/retry.go
+++ b/retry.go
@@ -4,20 +4,19 @@ package gosnowflake
 
 import (
 	"bytes"
+	"context"
 	"crypto/x509"
 	"fmt"
-	"github.com/google/uuid"
 	"io"
 	"math/rand"
 	"net/http"
 	"net/url"
 	"strconv"
 	"strings"
+	"sync"
 	"time"
 
-	"context"
-
-	"sync"
+	"github.com/google/uuid"
 )
 
 var random *rand.Rand
diff --git a/s3_util.go b/s3_util.go
index e8351c6..5b44cce 100644
--- a/s3_util.go
+++ b/s3_util.go
@@ -6,6 +6,7 @@ import (
 	"bytes"
 	"context"
 	"errors"
+	"fmt"
 	"os"
 	"strings"
 
@@ -35,7 +36,7 @@ type s3Location struct {
 	s3Path     string
 }
 
-func (util *snowflakeS3Util) createClient(info *execResponseStageInfo, useAccelerateEndpoint bool) cloudClient {
+func (util *snowflakeS3Util) createClient(info *execResponseStageInfo, useAccelerateEndpoint bool) (cloudClient, error) {
 	stageCredentials := info.Creds
 	var resolver s3.EndpointResolver
 	if info.EndPoint != "" {
@@ -50,7 +51,7 @@ func (util *snowflakeS3Util) createClient(info *execResponseStageInfo, useAccele
 			stageCredentials.AwsToken)),
 		EndpointResolver: resolver,
 		UseAccelerate:    useAccelerateEndpoint,
-	})
+	}), nil
 }
 
 type s3HeaderAPI interface {
@@ -58,12 +59,15 @@ type s3HeaderAPI interface {
 }
 
 // cloudUtil implementation
-func (util *snowflakeS3Util) getFileHeader(meta *fileMetadata, filename string) *fileHeader {
-	headObjInput := util.getS3Object(meta, filename)
+func (util *snowflakeS3Util) getFileHeader(meta *fileMetadata, filename string) (*fileHeader, error) {
+	headObjInput, err := util.getS3Object(meta, filename)
+	if err != nil {
+		return nil, err
+	}
 	var s3Cli s3HeaderAPI
 	s3Cli, ok := meta.client.(*s3.Client)
 	if !ok {
-		return nil
+		return nil, fmt.Errorf("could not parse client to s3.Client")
 	}
 	if meta.mockHeader != nil {
 		s3Cli = meta.mockHeader
@@ -78,14 +82,14 @@ func (util *snowflakeS3Util) getFileHeader(meta *fileMetadata, filename string)
 					digest:             "",
 					contentLength:      0,
 					encryptionMetadata: nil,
-				}
+				}, nil
 			} else if ae.ErrorCode() == expiredToken {
 				meta.resStatus = renewToken
-				return nil
+				return nil, fmt.Errorf("received expired token. renewing")
 			}
 			meta.resStatus = errStatus
 			meta.lastError = err
-			return nil
+			return nil, fmt.Errorf("error while retrieving header")
 		}
 	}
 
@@ -102,7 +106,7 @@ func (util *snowflakeS3Util) getFileHeader(meta *fileMetadata, filename string)
 		out.Metadata[sfcDigest],
 		out.ContentLength,
 		&encMeta,
-	}
+	}, nil
 }
 
 type s3UploadAPI interface {
@@ -126,7 +130,10 @@ func (util *snowflakeS3Util) uploadFile(
 		s3Meta[amzMatdesc] = encryptMeta.matdesc
 	}
 
-	s3loc := util.extractBucketNameAndPath(meta.stageInfo.Location)
+	s3loc, err := util.extractBucketNameAndPath(meta.stageInfo.Location)
+	if err != nil {
+		return err
+	}
 	s3path := s3loc.s3Path + strings.TrimLeft(meta.dstFileName, "/")
 
 	client, ok := meta.client.(*s3.Client)
@@ -144,7 +151,6 @@ func (util *snowflakeS3Util) uploadFile(
 		uploader = meta.mockUploader
 	}
 
-	var err error
 	if meta.srcStream != nil {
 		uploadStream := meta.srcStream
 		if meta.realSrcStream != nil {
@@ -157,7 +163,11 @@ func (util *snowflakeS3Util) uploadFile(
 			Metadata: s3Meta,
 		})
 	} else {
-		file, _ := os.Open(dataFile)
+		var file *os.File
+		file, err = os.Open(dataFile)
+		if err != nil {
+			return err
+		}
 		_, err = uploader.Upload(context.Background(), &s3.PutObjectInput{
 			Bucket:   &s3loc.bucketName,
 			Key:      &s3path,
@@ -192,7 +202,10 @@ func (util *snowflakeS3Util) nativeDownloadFile(
 	meta *fileMetadata,
 	fullDstFileName string,
 	maxConcurrency int64) error {
-	s3loc := util.extractBucketNameAndPath(meta.stageInfo.Location)
+	s3loc, err := util.extractBucketNameAndPath(meta.stageInfo.Location)
+	if err != nil {
+		return err
+	}
 	s3path := s3loc.s3Path + strings.TrimLeft(meta.dstFileName, "/")
 	client, ok := meta.client.(*s3.Client)
 	if !ok {
@@ -235,8 +248,11 @@ func (util *snowflakeS3Util) nativeDownloadFile(
 	return nil
 }
 
-func (util *snowflakeS3Util) extractBucketNameAndPath(location string) *s3Location {
-	stageLocation := expandUser(location)
+func (util *snowflakeS3Util) extractBucketNameAndPath(location string) (*s3Location, error) {
+	stageLocation, err := expandUser(location)
+	if err != nil {
+		return nil, err
+	}
 	bucketName := stageLocation
 	s3Path := ""
 
@@ -247,14 +263,17 @@ func (util *snowflakeS3Util) extractBucketNameAndPath(location string) *s3Locati
 			s3Path += "/"
 		}
 	}
-	return &s3Location{bucketName, s3Path}
+	return &s3Location{bucketName, s3Path}, nil
 }
 
-func (util *snowflakeS3Util) getS3Object(meta *fileMetadata, filename string) *s3.HeadObjectInput {
-	s3loc := util.extractBucketNameAndPath(meta.stageInfo.Location)
+func (util *snowflakeS3Util) getS3Object(meta *fileMetadata, filename string) (*s3.HeadObjectInput, error) {
+	s3loc, err := util.extractBucketNameAndPath(meta.stageInfo.Location)
+	if err != nil {
+		return nil, err
+	}
 	s3path := s3loc.s3Path + strings.TrimLeft(filename, "/")
 	return &s3.HeadObjectInput{
 		Bucket: &s3loc.bucketName,
 		Key:    &s3path,
-	}
+	}, nil
 }
diff --git a/storage_client.go b/storage_client.go
index 9f45f49..95aae4a 100644
--- a/storage_client.go
+++ b/storage_client.go
@@ -19,15 +19,15 @@ const (
 
 // implemented by localUtil and remoteStorageUtil
 type storageUtil interface {
-	createClient(*execResponseStageInfo, bool) cloudClient
+	createClient(*execResponseStageInfo, bool) (cloudClient, error)
 	uploadOneFileWithRetry(*fileMetadata) error
 	downloadOneFile(*fileMetadata) error
 }
 
 // implemented by snowflakeS3Util, snowflakeAzureUtil and snowflakeGcsUtil
 type cloudUtil interface {
-	createClient(*execResponseStageInfo, bool) cloudClient
-	getFileHeader(*fileMetadata, string) *fileHeader
+	createClient(*execResponseStageInfo, bool) (cloudClient, error)
+	getFileHeader(*fileMetadata, string) (*fileHeader, error)
 	uploadFile(string, *fileMetadata, *encryptMetadata, int, int64) error
 	nativeDownloadFile(*fileMetadata, string, int64) error
 }
@@ -49,7 +49,7 @@ func (rsu *remoteStorageUtil) getNativeCloudType(cli string) cloudUtil {
 }
 
 // call cloud utils' native create client methods
-func (rsu *remoteStorageUtil) createClient(info *execResponseStageInfo, useAccelerateEndpoint bool) cloudClient {
+func (rsu *remoteStorageUtil) createClient(info *execResponseStageInfo, useAccelerateEndpoint bool) (cloudClient, error) {
 	utilClass := rsu.getNativeCloudType(info.LocationType)
 	return utilClass.createClient(info, useAccelerateEndpoint)
 }
@@ -87,7 +87,10 @@ func (rsu *remoteStorageUtil) uploadOneFile(meta *fileMetadata) error {
 	maxRetry := defaultMaxRetry
 	for retry := 0; retry < maxRetry; retry++ {
 		if !meta.overwrite {
-			header := utilClass.getFileHeader(meta, meta.dstFileName)
+			header, err := utilClass.getFileHeader(meta, meta.dstFileName)
+			if err != nil {
+				return err
+			}
 			if header != nil && meta.resStatus == uploaded {
 				meta.dstFileSize = 0
 				meta.resStatus = skipped
@@ -162,9 +165,15 @@ func (rsu *remoteStorageUtil) uploadOneFileWithRetry(meta *fileMetadata) error {
 
 func (rsu *remoteStorageUtil) downloadOneFile(meta *fileMetadata) error {
 	fullDstFileName := path.Join(meta.localLocation, baseName(meta.dstFileName))
-	fullDstFileName = expandUser(fullDstFileName)
+	fullDstFileName, err := expandUser(fullDstFileName)
+	if err != nil {
+		return err
+	}
 	if !filepath.IsAbs(fullDstFileName) {
-		cwd, _ := os.Getwd()
+		cwd, err := os.Getwd()
+		if err != nil {
+			return err
+		}
 		fullDstFileName = filepath.Join(cwd, fullDstFileName)
 	}
 	baseDir, err := getDirectory()
@@ -178,7 +187,10 @@ func (rsu *remoteStorageUtil) downloadOneFile(meta *fileMetadata) error {
 	}
 
 	utilClass := rsu.getNativeCloudType(meta.stageInfo.LocationType)
-	header := utilClass.getFileHeader(meta, meta.srcFileName)
+	header, err := utilClass.getFileHeader(meta, meta.srcFileName)
+	if err != nil {
+		return err
+	}
 	if header != nil {
 		meta.srcFileSize = header.contentLength
 	}
@@ -193,7 +205,10 @@ func (rsu *remoteStorageUtil) downloadOneFile(meta *fileMetadata) error {
 		if meta.resStatus == downloaded {
 			if meta.encryptionMaterial != nil {
 				if meta.presignedURL != nil {
-					header = utilClass.getFileHeader(meta, meta.srcFileName)
+					header, err = utilClass.getFileHeader(meta, meta.srcFileName)
+					if err != nil {
+						return err
+					}
 				}
 				tmpDstFileName, err := decryptFile(header.encryptionMetadata,
 					meta.encryptionMaterial, fullDstFileName, 0, meta.tmpDir)


Test patch:
diff --git a/auth_test.go b/auth_test.go
index 879a016..8a55429 100644
--- a/auth_test.go
+++ b/auth_test.go
@@ -455,16 +455,17 @@ func TestUnitAuthenticateJWT(t *testing.T) {
 	sc.rest = sr
 
 	// A valid JWT token should pass
-	_, err = authenticate(context.TODO(), sc, []byte{}, []byte{})
-	if err != nil {
+	if _, err = authenticate(context.TODO(), sc, []byte{}, []byte{}); err != nil {
 		t.Fatalf("failed to run. err: %v", err)
 	}
 
 	// An invalid JWT token should not pass
-	invalidPrivateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
+	invalidPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+	if err != nil {
+		t.Error(err)
+	}
 	sc.cfg.PrivateKey = invalidPrivateKey
-	_, err = authenticate(context.TODO(), sc, []byte{}, []byte{})
-	if err == nil {
+	if _, err = authenticate(context.TODO(), sc, []byte{}, []byte{}); err == nil {
 		t.Fatalf("invalid token passed")
 	}
 }
diff --git a/benchmark/jsonresultset/jsonresultset_test.go b/benchmark/jsonresultset/jsonresultset_test.go
index 0b83020..039a9fd 100644
--- a/benchmark/jsonresultset/jsonresultset_test.go
+++ b/benchmark/jsonresultset/jsonresultset_test.go
@@ -64,7 +64,10 @@ func getDSN() (dsn string, cfg *sf.Config, err error) {
 		sf.MaxChunkDownloadWorkers = n0
 	}
 
-	portStr, _ := strconv.Atoi(port)
+	portStr, err := strconv.Atoi(port)
+	if err != nil {
+		return "", nil, err
+	}
 	cfg = &sf.Config{
 		Account:  account,
 		User:     user,
diff --git a/benchmark/largesetresult/largesetresult_test.go b/benchmark/largesetresult/largesetresult_test.go
index 39b57d7..493a7b4 100644
--- a/benchmark/largesetresult/largesetresult_test.go
+++ b/benchmark/largesetresult/largesetresult_test.go
@@ -48,7 +48,10 @@ func getDSN() (dsn string, cfg *sf.Config, err error) {
 	port := env("SNOWFLAKE_TEST_PORT", false)
 	protocol := env("SNOWFLAKE_TEST_PROTOCOL", false)
 
-	portStr, _ := strconv.Atoi(port)
+	portStr, err := strconv.Atoi(port)
+	if err != nil {
+		return "", nil, err
+	}
 	cfg = &sf.Config{
 		Account:  account,
 		User:     user,
diff --git a/bindings_test.go b/bindings_test.go
index 1c932b4..1fdf397 100644
--- a/bindings_test.go
+++ b/bindings_test.go
@@ -271,7 +271,10 @@ func testBindingArray(t *testing.T, bulk bool) {
 	byteArray := [][]byte{{0x01, 0x02, 0x03}, {0x04, 0x05, 0x06}, {0x07, 0x08, 0x09}}
 
 	now := time.Now()
-	loc, _ := time.LoadLocation(PSTLocation)
+	loc, err := time.LoadLocation(PSTLocation)
+	if err != nil {
+		t.Error(err)
+	}
 	ntzArray := []time.Time{now, now.Add(1), now.Add(2)}
 	ltzArray := []time.Time{now.Add(3).In(loc), now.Add(4).In(loc), now.Add(5).In(loc)}
 	tzArray := []time.Time{tz.Add(6).In(loc), tz.Add(7).In(loc), tz.Add(8).In(loc)}
diff --git a/chunk_test.go b/chunk_test.go
index 2104aac..0ef6159 100644
--- a/chunk_test.go
+++ b/chunk_test.go
@@ -325,9 +325,9 @@ func generateStreamChunkDownloaderChunks(urls []string, numRows, numCols int) (m
 }
 
 func generateStreamChunkRows(numRows, numCols int) [][]*string {
-	rows := [][]*string{}
+	var rows [][]*string
 	for i := 0; i < numRows; i++ {
-		cols := []*string{}
+		var cols []*string
 		for j := 0; j < numCols; j++ {
 			col := fmt.Sprintf("%d", rand.Intn(1000))
 			cols = append(cols, &col)
diff --git a/connection_test.go b/connection_test.go
index 1e4a10c..cf7c77c 100644
--- a/connection_test.go
+++ b/connection_test.go
@@ -278,7 +278,10 @@ func fetchResultByQueryID(
 	t *testing.T,
 	customGet FuncGetType,
 	expectedFetchErr *SnowflakeError) error {
-	config, _ := ParseDSN(dsn)
+	config, err := ParseDSN(dsn)
+	if err != nil {
+		return err
+	}
 	ctx := context.Background()
 	sc, err := buildSnowflakeConn(ctx, *config)
 	if customGet != nil {
@@ -355,7 +358,10 @@ func TestPrivateLink(t *testing.T) {
 }
 
 func TestGetQueryStatus(t *testing.T) {
-	config, _ := ParseDSN(dsn)
+	config, err := ParseDSN(dsn)
+	if err != nil {
+		t.Error(err)
+	}
 	ctx := context.Background()
 	sc, err := buildSnowflakeConn(ctx, *config)
 	if err != nil {
diff --git a/converter_test.go b/converter_test.go
index 33e96e5..70e6fd8 100644
--- a/converter_test.go
+++ b/converter_test.go
@@ -5,14 +5,15 @@ package gosnowflake
 import (
 	"database/sql/driver"
 	"fmt"
-	"github.com/apache/arrow/go/arrow"
-	"github.com/apache/arrow/go/arrow/array"
-	"github.com/apache/arrow/go/arrow/memory"
 	"math/big"
 	"math/cmplx"
 	"reflect"
 	"testing"
 	"time"
+
+	"github.com/apache/arrow/go/arrow"
+	"github.com/apache/arrow/go/arrow/array"
+	"github.com/apache/arrow/go/arrow/memory"
 )
 
 type tcGoTypeToSnowflake struct {
diff --git a/driver_test.go b/driver_test.go
index 32f92e2..7b821d8 100644
--- a/driver_test.go
+++ b/driver_test.go
@@ -2200,8 +2200,11 @@ func TestTimePrecision(t *testing.T) {
 	runTests(t, dsn, func(dbt *DBTest) {
 		dbt.mustExec("create or replace table z3 (t1 time(5))")
 		rows := dbt.mustQuery("select * from z3")
-		cols, _ := rows.ColumnTypes()
-		if pres, _, _ := cols[0].DecimalSize(); pres != 5 {
+		cols, err := rows.ColumnTypes()
+		if err != nil {
+			t.Error(err)
+		}
+		if pres, _, ok := cols[0].DecimalSize(); pres != 5 || !ok {
 			t.Fatalf("Wrong value returned. Got %v instead of 5.", pres)
 		}
 	})
diff --git a/encrypt_util_test.go b/encrypt_util_test.go
index dda757e..5c82221 100644
--- a/encrypt_util_test.go
+++ b/encrypt_util_test.go
@@ -50,9 +50,15 @@ func TestEncryptDecryptFile(t *testing.T) {
 	}
 	defer os.Remove(decryptedFile)
 
-	fd, _ = os.OpenFile(decryptedFile, os.O_RDONLY, os.ModePerm)
+	fd, err = os.OpenFile(decryptedFile, os.O_RDONLY, os.ModePerm)
+	if err != nil {
+		t.Error(err)
+	}
 	defer fd.Close()
-	content, _ := ioutil.ReadAll(fd)
+	content, err := ioutil.ReadAll(fd)
+	if err != nil {
+		t.Error(err)
+	}
 	if string(content) != data {
 		t.Fatalf("data did not match content. expected: %v, got: %v", data, string(content))
 	}
@@ -66,8 +72,14 @@ func TestEncryptDecryptLargeFile(t *testing.T) {
 	}
 	numberOfFiles := 1
 	numberOfLines := 10000
-	tmpDir, _ := ioutil.TempDir("", "data")
-	tmpDir = generateKLinesOfNFiles(numberOfLines, numberOfFiles, false, tmpDir)
+	tmpDir, err := ioutil.TempDir("", "data")
+	if err != nil {
+		t.Error(err)
+	}
+	tmpDir, err = generateKLinesOfNFiles(numberOfLines, numberOfFiles, false, tmpDir)
+	if err != nil {
+		t.Error(err)
+	}
 	defer os.RemoveAll(tmpDir)
 	files, err := filepath.Glob(filepath.Join(tmpDir, "file*"))
 	if err != nil {
@@ -87,7 +99,10 @@ func TestEncryptDecryptLargeFile(t *testing.T) {
 	defer os.Remove(decryptedFile)
 
 	cnt := 0
-	fd, _ := os.OpenFile(decryptedFile, os.O_RDONLY, os.ModePerm)
+	fd, err := os.OpenFile(decryptedFile, os.O_RDONLY, os.ModePerm)
+	if err != nil {
+		t.Error(err)
+	}
 	scanner := bufio.NewScanner(fd)
 	for scanner.Scan() {
 		cnt++
@@ -100,13 +115,19 @@ func TestEncryptDecryptLargeFile(t *testing.T) {
 	}
 }
 
-func generateKLinesOfNFiles(k int, n int, compress bool, tmpDir string) string {
+func generateKLinesOfNFiles(k int, n int, compress bool, tmpDir string) (string, error) {
 	if tmpDir == "" {
-		tmpDir, _ = ioutil.TempDir(tmpDir, "data")
+		_, err := ioutil.TempDir(tmpDir, "data")
+		if err != nil {
+			return "", err
+		}
 	}
 	for i := 0; i < n; i++ {
 		fname := path.Join(tmpDir, "file"+strconv.FormatInt(int64(i), 10))
-		f, _ := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, os.ModePerm)
+		f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, os.ModePerm)
+		if err != nil {
+			return "", err
+		}
 		for j := 0; j < k; j++ {
 			num := rand.Float64() * 10000
 			min := time.Date(1970, 1, 0, 0, 0, 0, 0, time.UTC).Unix()
@@ -132,22 +153,34 @@ func generateKLinesOfNFiles(k int, n int, compress bool, tmpDir string) string {
 		if compress {
 			if !isWindows {
 				gzipCmd := exec.Command("gzip", filepath.Join(tmpDir, "file"+strconv.FormatInt(int64(i), 10)))
-				gzipOut, _ := gzipCmd.StdoutPipe()
-				gzipErr, _ := gzipCmd.StderrPipe()
+				gzipOut, err := gzipCmd.StdoutPipe()
+				if err != nil {
+					return "", err
+				}
+				gzipErr, err := gzipCmd.StderrPipe()
+				if err != nil {
+					return "", err
+				}
 				gzipCmd.Start()
 				ioutil.ReadAll(gzipOut)
 				ioutil.ReadAll(gzipErr)
 				gzipCmd.Wait()
 			} else {
-				fOut, _ := os.OpenFile(fname+".gz", os.O_CREATE|os.O_WRONLY, os.ModePerm)
+				fOut, err := os.OpenFile(fname+".gz", os.O_CREATE|os.O_WRONLY, os.ModePerm)
+				if err != nil {
+					return "", err
+				}
 				w := gzip.NewWriter(fOut)
-				fIn, _ := os.OpenFile(fname, os.O_RDONLY, os.ModePerm)
-				if _, err := io.Copy(w, fIn); err != nil {
-					return ""
+				fIn, err := os.OpenFile(fname, os.O_RDONLY, os.ModePerm)
+				if err != nil {
+					return "", err
+				}
+				if _, err = io.Copy(w, fIn); err != nil {
+					return "", err
 				}
 				w.Close()
 			}
 		}
 	}
-	return tmpDir
+	return tmpDir, nil
 }
diff --git a/priv_key_test.go b/priv_key_test.go
index 70fa3b2..17d5e3d 100644
--- a/priv_key_test.go
+++ b/priv_key_test.go
@@ -105,9 +105,15 @@ func TestJWTAuthentication(t *testing.T) {
 	db.Close()
 
 	// Test that an invalid private key cannot pass
-	invalidPrivateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
+	invalidPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
+	if err != nil {
+		t.Error(err)
+	}
 	jwtDSN = appendPrivateKeyString(&dsn, invalidPrivateKey)
-	db, _ = sql.Open("snowflake", jwtDSN)
+	db, err = sql.Open("snowflake", jwtDSN)
+	if err != nil {
+		t.Error(err)
+	}
 	if _, err = db.Exec("SELECT 1"); err == nil {
 		t.Fatalf("An invalid jwt token can pass")
 	}
diff --git a/put_get_test.go b/put_get_test.go
index 64bbfa7..8c259e2 100644
--- a/put_get_test.go
+++ b/put_get_test.go
@@ -21,11 +21,17 @@ func TestPutError(t *testing.T) {
 	if isWindows {
 		t.Skip("permission model is different")
 	}
-	tmpDir, _ := ioutil.TempDir("", "putfiledir")
+	tmpDir, err := ioutil.TempDir("", "putfiledir")
+	if err != nil {
+		t.Error(err)
+	}
 	defer os.RemoveAll(tmpDir)
 	file1 := filepath.Join(tmpDir, "file1")
 	remoteLocation := filepath.Join(tmpDir, "remote_loc")
-	f, _ := os.OpenFile(file1, os.O_CREATE|os.O_WRONLY, os.ModePerm)
+	f, err := os.OpenFile(file1, os.O_CREATE|os.O_WRONLY, os.ModePerm)
+	if err != nil {
+		t.Error(err)
+	}
 	f.WriteString("test1")
 	os.Chmod(file1, 0000)
 
@@ -103,18 +109,30 @@ func cleanupPut(dbt *DBTest, td *tcPutGetData) {
 }
 
 func createTestData(dbt *DBTest) (*tcPutGetData, error) {
-	keyID, _ := os.LookupEnv("AWS_ACCESS_KEY_ID")
-	secretKey, _ := os.LookupEnv("AWS_SECRET_ACCESS_KEY")
+	keyID, ok := os.LookupEnv("AWS_ACCESS_KEY_ID")
+	if !ok {
+		return nil, fmt.Errorf("key id invalid")
+	}
+	secretKey, ok := os.LookupEnv("AWS_SECRET_ACCESS_KEY")
+	if !ok {
+		return nil, fmt.Errorf("secret key invalid")
+	}
 	bucket, present := os.LookupEnv("SF_AWS_USER_BUCKET")
 	if !present {
-		usr, _ := usr.Current()
+		usr, err := usr.Current()
+		if err != nil {
+			return nil, err
+		}
 		bucket = fmt.Sprintf("sfc-dev1-regression/%v/reg", usr.Username)
 	}
 	uniqueName := randomString(10)
 	database := fmt.Sprintf("%v_db", uniqueName)
 	wh := fmt.Sprintf("%v_wh", uniqueName)
 
-	dir, _ := os.Getwd()
+	dir, err := os.Getwd()
+	if err != nil {
+		return nil, err
+	}
 	ret := tcPutGetData{
 		dir,
 		keyID,
@@ -203,16 +221,22 @@ func TestPutWithAutoCompressFalse(t *testing.T) {
 	if runningOnGithubAction() && !runningOnAWS() {
 		t.Skip("skipping non aws environment")
 	}
-	tmpDir, _ := ioutil.TempDir("", "put")
+	tmpDir, err := ioutil.TempDir("", "put")
+	if err != nil {
+		t.Error(err)
+	}
 	defer os.RemoveAll(tmpDir)
 	testData := filepath.Join(tmpDir, "data.txt")
-	f, _ := os.OpenFile(testData, os.O_CREATE|os.O_WRONLY, os.ModePerm)
+	f, err := os.OpenFile(testData, os.O_CREATE|os.O_WRONLY, os.ModePerm)
+	if err != nil {
+		t.Error(err)
+	}
 	f.WriteString("test1,test2\ntest3,test4")
 	f.Sync()
 	defer f.Close()
 
 	runTests(t, dsn, func(dbt *DBTest) {
-		if _, err := dbt.db.Exec("use role sysadmin"); err != nil {
+		if _, err = dbt.db.Exec("use role sysadmin"); err != nil {
 			t.Skip("snowflake admin account not accessible")
 		}
 		dbt.mustExec("rm @~/test_put_uncompress_file")
@@ -237,10 +261,16 @@ func TestPutWithAutoCompressFalse(t *testing.T) {
 }
 
 func TestPutOverwrite(t *testing.T) {
-	tmpDir, _ := ioutil.TempDir("", "data")
+	tmpDir, err := ioutil.TempDir("", "data")
+	if err != nil {
+		t.Error(err)
+	}
 	defer os.RemoveAll(tmpDir)
 	testData := filepath.Join(tmpDir, "data.txt")
-	f, _ := os.OpenFile(testData, os.O_CREATE|os.O_RDWR, os.ModePerm)
+	f, err := os.OpenFile(testData, os.O_CREATE|os.O_RDWR, os.ModePerm)
+	if err != nil {
+		t.Error(err)
+	}
 	f.WriteString("test1,test2\ntest3,test4\n")
 	f.Close()
 
@@ -323,7 +353,10 @@ func TestPutGetStream(t *testing.T) {
 }
 
 func testPutGet(t *testing.T, isStream bool) {
-	tmpDir, _ := ioutil.TempDir("", "put_get")
+	tmpDir, err := ioutil.TempDir("", "put_get")
+	if err != nil {
+		t.Error(err)
+	}
 	defer os.RemoveAll(tmpDir)
 	fname := filepath.Join(tmpDir, "test_put_get.txt.gz")
 	originalContents := "123,test1\n456,test2\n"
@@ -340,7 +373,10 @@ func testPutGet(t *testing.T, isStream bool) {
 	runTests(t, dsn, func(dbt *DBTest) {
 		dbt.mustExec("create or replace table " + tableName +
 			" (a int, b string)")
-		fileStream, _ := os.OpenFile(fname, os.O_RDONLY, os.ModePerm)
+		fileStream, err := os.OpenFile(fname, os.O_RDONLY, os.ModePerm)
+		if err != nil {
+			t.Error(err)
+		}
 		defer func() {
 			defer dbt.mustExec("drop table " + tableName)
 			if fileStream != nil {
@@ -408,7 +444,10 @@ func testPutGet(t *testing.T, isStream bool) {
 			t.Fatal(err)
 		}
 		fileName := files[0]
-		f, _ := os.Open(fileName)
+		f, err := os.Open(fileName)
+		if err != nil {
+			t.Error(err)
+		}
 		defer f.Close()
 		gz, err := gzip.NewReader(f)
 		if err != nil {
diff --git a/put_get_user_stage_test.go b/put_get_user_stage_test.go
index 189e0a7..af52545 100644
--- a/put_get_user_stage_test.go
+++ b/put_get_user_stage_test.go
@@ -29,12 +29,21 @@ func putGetUserStage(t *testing.T, tmpDir string, numberOfFiles int, numberOfLin
 	if os.Getenv("AWS_SECRET_ACCESS_KEY") == "" {
 		t.Fatal("no aws secret access key found")
 	}
-	tmpDir, _ = ioutil.TempDir(tmpDir, "data")
-	tmpDir = generateKLinesOfNFiles(numberOfLines, numberOfFiles, false, tmpDir)
+	tmpDir, err := ioutil.TempDir(tmpDir, "data")
+	if err != nil {
+		t.Error(err)
+	}
+	tmpDir, err = generateKLinesOfNFiles(numberOfLines, numberOfFiles, false, tmpDir)
+	if err != nil {
+		t.Error(err)
+	}
 	defer os.RemoveAll(tmpDir)
 	var files string
 	if isStream {
-		list, _ := ioutil.ReadDir(tmpDir)
+		list, err := ioutil.ReadDir(tmpDir)
+		if err != nil {
+			t.Error(err)
+		}
 		file := list[0].Name()
 		files = filepath.Join(tmpDir, file)
 	} else {
@@ -83,7 +92,10 @@ func putGetUserStage(t *testing.T, tmpDir string, numberOfFiles int, numberOfLin
 		if rows.Next() {
 			rows.Scan(&cnt)
 		}
-		count, _ := strconv.Atoi(cnt)
+		count, err := strconv.Atoi(cnt)
+		if err != nil {
+			t.Error(err)
+		}
 		if count != numberOfFiles*numberOfLines {
 			t.Errorf("count did not match expected number. count: %v, expected: %v", count, numberOfFiles*numberOfLines)
 		}
diff --git a/put_get_with_aws_test.go b/put_get_with_aws_test.go
index dda9864..89c30d2 100644
--- a/put_get_with_aws_test.go
+++ b/put_get_with_aws_test.go
@@ -87,7 +87,10 @@ func TestPutWithInvalidToken(t *testing.T) {
 	if !runningOnAWS() {
 		t.Skip("skipping non aws environment")
 	}
-	tmpDir, _ := ioutil.TempDir("", "aws_put")
+	tmpDir, err := ioutil.TempDir("", "aws_put")
+	if err != nil {
+		t.Error(err)
+	}
 	defer os.RemoveAll(tmpDir)
 	fname := filepath.Join(tmpDir, "test_put_get_with_aws.txt.gz")
 	originalContents := "123,test1\n456,test2\n"
@@ -100,7 +103,10 @@ func TestPutWithInvalidToken(t *testing.T) {
 		t.Fatal("could not write to gzip file")
 	}
 
-	config, _ := ParseDSN(dsn)
+	config, err := ParseDSN(dsn)
+	if err != nil {
+		t.Error(err)
+	}
 	sc, err := buildSnowflakeConn(context.Background(), *config)
 	if err != nil {
 		t.Fatal(err)
@@ -116,9 +122,12 @@ func TestPutWithInvalidToken(t *testing.T) {
 	}
 	defer sc.Exec("drop table "+tableName, nil)
 
-	jsonBody, _ := json.Marshal(execRequest{
+	jsonBody, err := json.Marshal(execRequest{
 		SQLText: fmt.Sprintf("put 'file://%v' @%%%v", fname, tableName),
 	})
+	if err != nil {
+		t.Error(err)
+	}
 	headers := getHeaders()
 	headers[httpHeaderAccept] = headerContentTypeApplicationJSON
 	data, err := sc.rest.FuncPostQuery(
@@ -129,12 +138,22 @@ func TestPutWithInvalidToken(t *testing.T) {
 	}
 
 	s3Util := new(snowflakeS3Util)
-	client := s3Util.createClient(&data.Data.StageInfo, false).(*s3.Client)
+	s3Cli, err := s3Util.createClient(&data.Data.StageInfo, false)
+	if err != nil {
+		t.Error(err)
+	}
+	client := s3Cli.(*s3.Client)
 
-	s3Loc := s3Util.extractBucketNameAndPath(data.Data.StageInfo.Location)
+	s3Loc, err := s3Util.extractBucketNameAndPath(data.Data.StageInfo.Location)
+	if err != nil {
+		t.Error(err)
+	}
 	s3Path := s3Loc.s3Path + baseName(fname) + ".gz"
 
-	f, _ := os.Open(fname)
+	f, err := os.Open(fname)
+	if err != nil {
+		t.Error(err)
+	}
 	defer f.Close()
 	uploader := manager.NewUploader(client)
 	if _, err = uploader.Upload(context.Background(), &s3.PutObjectInput{
@@ -160,7 +179,11 @@ func TestPutWithInvalidToken(t *testing.T) {
 			AwsSecretKey: data.Data.StageInfo.Creds.AwsSecretKey,
 		},
 	}
-	client = s3Util.createClient(&info, false).(*s3.Client)
+	s3Cli, err = s3Util.createClient(&info, false)
+	if err != nil {
+		t.Error(err)
+	}
+	client = s3Cli.(*s3.Client)
 
 	uploader = manager.NewUploader(client)
 	if _, err = uploader.Upload(context.Background(), &s3.PutObjectInput{
@@ -176,7 +199,10 @@ func TestPretendToPutButList(t *testing.T) {
 	if runningOnGithubAction() && !runningOnAWS() {
 		t.Skip("skipping non aws environment")
 	}
-	tmpDir, _ := ioutil.TempDir("", "aws_put")
+	tmpDir, err := ioutil.TempDir("", "aws_put")
+	if err != nil {
+		t.Error(err)
+	}
 	defer os.RemoveAll(tmpDir)
 	fname := filepath.Join(tmpDir, "test_put_get_with_aws.txt.gz")
 	originalContents := "123,test1\n456,test2\n"
@@ -189,7 +215,10 @@ func TestPretendToPutButList(t *testing.T) {
 		t.Fatal("could not write to gzip file")
 	}
 
-	config, _ := ParseDSN(dsn)
+	config, err := ParseDSN(dsn)
+	if err != nil {
+		t.Error(err)
+	}
 	sc, err := buildSnowflakeConn(context.Background(), *config)
 	if err != nil {
 		t.Fatal(err)
@@ -205,9 +234,12 @@ func TestPretendToPutButList(t *testing.T) {
 	}
 	defer sc.Exec("drop table "+tableName, nil)
 
-	jsonBody, _ := json.Marshal(execRequest{
+	jsonBody, err := json.Marshal(execRequest{
 		SQLText: fmt.Sprintf("put 'file://%v' @%%%v", fname, tableName),
 	})
+	if err != nil {
+		t.Error(err)
+	}
 	headers := getHeaders()
 	headers[httpHeaderAccept] = headerContentTypeApplicationJSON
 	data, err := sc.rest.FuncPostQuery(
@@ -218,7 +250,11 @@ func TestPretendToPutButList(t *testing.T) {
 	}
 
 	s3Util := new(snowflakeS3Util)
-	client := s3Util.createClient(&data.Data.StageInfo, false).(*s3.Client)
+	s3Cli, err := s3Util.createClient(&data.Data.StageInfo, false)
+	if err != nil {
+		t.Error(err)
+	}
+	client := s3Cli.(*s3.Client)
 	if _, err = client.ListBuckets(context.Background(),
 		&s3.ListBucketsInput{}); err == nil {
 		t.Fatal("list buckets should fail")
diff --git a/restful_test.go b/restful_test.go
index 1c3ab34..7933c37 100644
--- a/restful_test.go
+++ b/restful_test.go
@@ -114,7 +114,10 @@ func postTestAfterRenew(_ context.Context, _ *snowflakeRestful, _ *url.URL, _ ma
 func cancelTestRetry(ctx context.Context, sr *snowflakeRestful, requestID uuid.UUID, timeout time.Duration) error {
 	ctxRetry := getCancelRetry(ctx)
 	u := url.URL{}
-	reqByte, _ := json.Marshal(make(map[string]string))
+	reqByte, err := json.Marshal(make(map[string]string))
+	if err != nil {
+		return err
+	}
 	resp, err := sr.FuncPost(ctx, sr, &u, getHeaders(), reqByte, timeout, false)
 	if err != nil {
 		return err
diff --git a/s3_util_test.go b/s3_util_test.go
index d24f987..a149f64 100644
--- a/s3_util_test.go
+++ b/s3_util_test.go
@@ -30,7 +30,10 @@ func TestExtractBucketNameAndPath(t *testing.T) {
 		{"sfc-dev1-regression///", "sfc-dev1-regression", "//"},
 	}
 	for _, test := range testcases {
-		s3Loc := s3util.extractBucketNameAndPath(test.in)
+		s3Loc, err := s3util.extractBucketNameAndPath(test.in)
+		if err != nil {
+			t.Error(err)
+		}
 		if s3Loc.bucketName != test.bucket {
 			t.Errorf("failed. in: %v, expected: %v, got: %v", test.in, test.bucket, s3Loc.bucketName)
 		}
@@ -58,14 +61,21 @@ func TestUploadOneFileToS3WSAEConnAborted(t *testing.T) {
 		LocationType: "S3",
 	}
 	initialParallel := int64(100)
-	dir, _ := os.Getwd()
+	dir, err := os.Getwd()
+	if err != nil {
+		t.Error(err)
+	}
 
+	s3Cli, err := new(snowflakeS3Util).createClient(&info, false)
+	if err != nil {
+		t.Error(err)
+	}
 	uploadMeta := fileMetadata{
 		name:              "data1.txt.gz",
 		stageLocationType: "S3",
 		noSleepingTime:    true,
 		parallel:          initialParallel,
-		client:            new(snowflakeS3Util).createClient(&info, false),
+		client:            s3Cli,
 		sha256Digest:      "123456789abcdef",
 		stageInfo:         &info,
 		dstFileName:       "data1.txt.gz",
@@ -123,14 +133,21 @@ func TestUploadOneFileToS3ConnReset(t *testing.T) {
 		LocationType: "S3",
 	}
 	initialParallel := int64(100)
-	dir, _ := os.Getwd()
+	dir, err := os.Getwd()
+	if err != nil {
+		t.Error(err)
+	}
 
+	s3Cli, err := new(snowflakeS3Util).createClient(&info, false)
+	if err != nil {
+		t.Error(err)
+	}
 	uploadMeta := fileMetadata{
 		name:              "data1.txt.gz",
 		stageLocationType: "S3",
 		noSleepingTime:    true,
 		parallel:          initialParallel,
-		client:            new(snowflakeS3Util).createClient(&info, false),
+		client:            s3Cli,
 		sha256Digest:      "123456789abcdef",
 		stageInfo:         &info,
 		dstFileName:       "data1.txt.gz",
@@ -170,14 +187,21 @@ func TestUploadFileWithS3UploadFailedError(t *testing.T) {
 		LocationType: "S3",
 	}
 	initialParallel := int64(100)
-	dir, _ := os.Getwd()
+	dir, err := os.Getwd()
+	if err != nil {
+		t.Error(err)
+	}
 
+	s3Cli, err := new(snowflakeS3Util).createClient(&info, false)
+	if err != nil {
+		t.Error(err)
+	}
 	uploadMeta := fileMetadata{
 		name:              "data1.txt.gz",
 		stageLocationType: "S3",
 		noSleepingTime:    true,
 		parallel:          initialParallel,
-		client:            new(snowflakeS3Util).createClient(&info, false),
+		client:            s3Cli,
 		sha256Digest:      "123456789abcdef",
 		stageInfo:         &info,
 		dstFileName:       "data1.txt.gz",
@@ -231,7 +255,7 @@ func TestGetHeadExpiryError(t *testing.T) {
 			}
 		}),
 	}
-	if header := new(snowflakeS3Util).getFileHeader(&meta, "file.txt"); header != nil {
+	if header, err := new(snowflakeS3Util).getFileHeader(&meta, "file.txt"); header != nil || err == nil {
 		t.Fatalf("expected null header, got: %v", header)
 	}
 	if meta.resStatus != renewToken {
@@ -250,7 +274,7 @@ func TestGetHeaderUnexpectedError(t *testing.T) {
 			}
 		}),
 	}
-	if header := new(snowflakeS3Util).getFileHeader(&meta, "file.txt"); header != nil {
+	if header, err := new(snowflakeS3Util).getFileHeader(&meta, "file.txt"); header != nil || err == nil {
 		t.Fatalf("expected null header, got: %v", header)
 	}
 	if meta.resStatus != errStatus {
diff --git a/statement_test.go b/statement_test.go
index ebb9b0f..7b741e8 100644
--- a/statement_test.go
+++ b/statement_test.go
@@ -25,17 +25,19 @@ func TestGetQueryID(t *testing.T) {
 	defer db.Close()
 
 	ctx := context.TODO()
-	conn, _ := db.Conn(ctx)
+	conn, err := db.Conn(ctx)
+	if err != nil {
+		t.Error(err)
+	}
 
-	if err := conn.Raw(func(x interface{}) error {
+	if err = conn.Raw(func(x interface{}) error {
 		rows, err := x.(driver.QueryerContext).QueryContext(ctx, "select 1", nil)
 		if err != nil {
 			return err
 		}
 		defer rows.Close()
 
-		_, err = x.(driver.ConnPrepareContext).PrepareContext(ctx, "selectt 1")
-		if err == nil {
+		if _, err = x.(driver.ConnPrepareContext).PrepareContext(ctx, "selectt 1"); err == nil {
 			t.Fatal("should have failed to execute query")
 		}
 		if driverErr, ok := err.(*SnowflakeError); ok {
@@ -102,8 +104,11 @@ func TestE2EFetchResultByID(t *testing.T) {
 	}
 
 	ctx := context.Background()
-	conn, _ := db.Conn(ctx)
-	if err := conn.Raw(func(x interface{}) error {
+	conn, err := db.Conn(ctx)
+	if err != nil {
+		t.Error(err)
+	}
+	if err = conn.Raw(func(x interface{}) error {
 		stmt, err := x.(driver.ConnPrepareContext).PrepareContext(ctx, "select * from test_fetch_result")
 		if err != nil {
 			return err
diff --git a/telemetry_test.go b/telemetry_test.go
index 4dc960d..69867ca 100644
--- a/telemetry_test.go
+++ b/telemetry_test.go
@@ -11,7 +11,10 @@ import (
 )
 
 func TestTelemetryAddLog(t *testing.T) {
-	config, _ := ParseDSN(dsn)
+	config, err := ParseDSN(dsn)
+	if err != nil {
+		t.Error(err)
+	}
 	sc, err := buildSnowflakeConn(context.Background(), *config)
 	if err != nil {
 		t.Fatal(err)
@@ -49,7 +52,10 @@ func TestTelemetryAddLog(t *testing.T) {
 }
 
 func TestTelemetrySQLException(t *testing.T) {
-	config, _ := ParseDSN(dsn)
+	config, err := ParseDSN(dsn)
+	if err != nil {
+		t.Error(err)
+	}
 	sc, err := buildSnowflakeConn(context.Background(), *config)
 	if err != nil {
 		t.Fatal(err)
@@ -88,7 +94,10 @@ func TestTelemetrySQLException(t *testing.T) {
 }
 
 func TestDisableTelemetry(t *testing.T) {
-	config, _ := ParseDSN(dsn)
+	config, err := ParseDSN(dsn)
+	if err != nil {
+		t.Error(err)
+	}
 	config.DisableTelemetry = true
 	sc, err := buildSnowflakeConn(context.Background(), *config)
 	if err != nil {