Skip to content

Commit

Permalink
Merge pull request #125 from aeneasr/use-error-as
Browse files Browse the repository at this point in the history
fix: user errors.As for error type assertion
  • Loading branch information
rafiss committed Feb 8, 2022
2 parents 7a4e302 + c787987 commit 3059636
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 25 deletions.
17 changes: 0 additions & 17 deletions crdb/error.go
Expand Up @@ -16,23 +16,6 @@ package crdb

import "fmt"

// errorCause returns the original cause of the error, if possible. An
// error has a proximate cause if it's type is compatible with Go's
// errors.Unwrap() or pkg/errors' Cause(); the original cause is the
// end of the causal chain.
func errorCause(err error) error {
for err != nil {
if c, ok := err.(interface{ Cause() error }); ok {
err = c.Cause()
} else if c, ok := err.(interface{ Unwrap() error }); ok {
err = c.Unwrap()
} else {
break
}
}
return err
}

type txError struct {
cause error
}
Expand Down
18 changes: 10 additions & 8 deletions crdb/tx.go
Expand Up @@ -19,6 +19,7 @@ package crdb
import (
"context"
"database/sql"
"errors"

"github.com/lib/pq"
)
Expand Down Expand Up @@ -193,16 +194,17 @@ func errIsRetryable(err error) bool {
}

func errCode(err error) string {
switch t := errorCause(err).(type) {
case *pq.Error:
return string(t.Code)

case errWithSQLState:
return t.SQLState()
var pqe *pq.Error
if errors.As(err, &pqe) {
return string(pqe.Code)
}

default:
return ""
var sqlErr errWithSQLState
if errors.As(err, &sqlErr) {
return sqlErr.SQLState()
}

return ""
}

// errWithSQLState is implemented by pgx (pgconn.PgError).
Expand Down

0 comments on commit 3059636

Please sign in to comment.