Skip to content

Commit

Permalink
Use errors.As instead of manual type assertions
Browse files Browse the repository at this point in the history
Signed-off-by: mprahl <[email protected]>
  • Loading branch information
mprahl authored and openshift-merge-bot[bot] committed Feb 29, 2024
1 parent 394307d commit adb2ede
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,9 @@ func RecordLocalClusterComplianceEvent(
// If it's a unique constraint violation, then the event is a duplicate and can be ignored. If it's a foreign
// key violation, that means the database experienced data loss and the foreign key is invalid, so the
// compliance event can't be recorded.
if pqErr, ok := err.(*pq.Error); ok { //nolint: errorlint
var pqErr *pq.Error

if errors.As(err, &pqErr) {
if pqErr.Code == postgresUniqueViolationCode {
return nil
}
Expand Down
21 changes: 9 additions & 12 deletions controllers/complianceeventsapi/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -759,17 +759,13 @@ func getSingleComplianceEvent(db *sql.DB, w http.ResponseWriter,
// as a convenience so that the keys don't need to be explicitly set to interface{} types when using the
// `getPqErrKeyVals(err, "key1", "val1")...“ syntax.
func getPqErrKeyVals(err error, additionalKeyVals ...interface{}) []interface{} {
unwrappedErr := err
var pqErr *pq.Error

for unwrappedErr != nil {
if pqErr, ok := unwrappedErr.(*pq.Error); ok { //nolint: errorlint
return append(
[]interface{}{"dbMessage", pqErr.Message, "dbDetail", pqErr.Detail, "dbCode", pqErr.Code},
additionalKeyVals...,
)
}

unwrappedErr = errors.Unwrap(unwrappedErr)
if errors.As(err, &pqErr) {
return append(
[]interface{}{"dbMessage", pqErr.Message, "dbDetail", pqErr.Detail, "dbCode", pqErr.Code},
additionalKeyVals...,
)
}

return additionalKeyVals
Expand Down Expand Up @@ -1083,8 +1079,9 @@ func postComplianceEvent(serverContext *ComplianceServerCtx, cfg *rest.Config, w
return
}

pqErr, ok := err.(*pq.Error) //nolint:errorlint
if ok && pqErr.Code == postgresForeignKeyViolationCode {
var pqErr *pq.Error

if errors.As(err, &pqErr) && pqErr.Code == postgresForeignKeyViolationCode {
// This can only happen if the cache is out of date due to data loss in the database because if the
// database ID is provided, it is validated against the database.
log.Info(
Expand Down

0 comments on commit adb2ede

Please sign in to comment.