github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/persistence/sql_error_mapper.go (about) 1 package persistence 2 3 import ( 4 "context" 5 "database/sql" 6 7 "github.com/kyma-incubator/compass/components/director/pkg/apperrors" 8 "github.com/kyma-incubator/compass/components/director/pkg/log" 9 "github.com/kyma-incubator/compass/components/director/pkg/resource" 10 11 "github.com/lib/pq" 12 "github.com/pkg/errors" 13 ) 14 15 // MapSQLError missing godoc 16 func MapSQLError(ctx context.Context, err error, resourceType resource.Type, sqlOperation resource.SQLOperation, format string, args ...interface{}) error { 17 if err == nil { 18 return nil 19 } 20 21 loggedErr := errors.Wrapf(err, format, args...) 22 if errors.Is(err, context.DeadlineExceeded) { 23 log.C(ctx).WithError(loggedErr).Errorf("Timeout error on SQL query") 24 return apperrors.NewInternalError("Maximum processing timeout reached") 25 } 26 27 if err == sql.ErrNoRows { 28 log.C(ctx).WithError(loggedErr).Errorf("SQL: no rows in result set for '%s' resource type", resourceType) 29 return apperrors.NewNotFoundErrorWithType(resourceType) 30 } 31 32 pgErr, ok := err.(*pq.Error) 33 if !ok { 34 log.C(ctx).WithError(loggedErr).Errorf("Error while casting to postgres error") 35 return apperrors.NewInternalError("Unexpected error while executing SQL query") 36 } 37 38 log.C(ctx).WithError(loggedErr).Errorf("SQL Error. Caused by: %s. DETAILS: %s", pgErr.Message, pgErr.Detail) 39 40 switch pgErr.Code { 41 case NotNullViolation: 42 return apperrors.NewNotNullViolationError(resourceType) 43 case CheckViolation: 44 return apperrors.NewCheckViolationError(resourceType) 45 case UniqueViolation: 46 return apperrors.NewNotUniqueError(resourceType) 47 case ForeignKeyViolation: 48 return apperrors.NewForeignKeyInvalidOperationError(sqlOperation, resourceType) 49 } 50 51 return apperrors.NewInternalError("Unexpected error while executing SQL query") 52 }