Skip to content

Commit

Permalink
Enhance googleapi error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
eugenepaniot committed Jan 17, 2023
1 parent 4cdaa50 commit 245699c
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions mysql/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import (
"time"

"github.com/go-sql-driver/mysql"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-version"
"google.golang.org/api/googleapi"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
Expand Down Expand Up @@ -312,15 +314,15 @@ func connectToMySQLInternal(ctx context.Context, conf *MySQLConfiguration) (*One
retryError := resource.RetryContext(ctx, conf.ConnectRetryTimeoutSec, func() *resource.RetryError {
db, err = sql.Open(driverName, dsn)
if err != nil {
if mysqlErrorNumber(err) == unknownVarErrCode || ctx.Err() != nil {
if mysqlErrorNumber(err) == unknownVarErrCode || cloudsqlErrorNumber(err) != 0 || ctx.Err() != nil {
return resource.NonRetryableError(err)
}
return resource.RetryableError(err)
}

err = db.PingContext(ctx)
if err != nil {
if mysqlErrorNumber(err) == unknownVarErrCode || ctx.Err() != nil {
if mysqlErrorNumber(err) == unknownVarErrCode || cloudsqlErrorNumber(err) != 0 || ctx.Err() != nil {
return resource.NonRetryableError(err)
}

Expand Down Expand Up @@ -359,3 +361,20 @@ func mysqlErrorNumber(err error) uint16 {
}
return me.Number
}

func cloudsqlErrorNumber(err error) int {
if err == nil {
return 0
}

if e, ok := err.(*googleapi.Error); ok {
return e.Code
} else if !ok && errwrap.ContainsType(err, &googleapi.Error{}) {
e := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
if e.Code >= 400 && e.Code < 500 {
return e.Code
}
}

return 0
}

0 comments on commit 245699c

Please sign in to comment.