Skip to content

Commit

Permalink
Return nicer erorr messages if a token or a profile already exist (#1406
Browse files Browse the repository at this point in the history
)

We were returning just an internal error which is really confusing.
  • Loading branch information
jhrozek authored Nov 2, 2023
1 parent 1baa7ab commit a449e5b
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
4 changes: 3 additions & 1 deletion internal/controlplane/handlers_oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,9 @@ func (s *Server) StoreProviderToken(ctx context.Context,
_, err = s.store.CreateAccessToken(ctx, db.CreateAccessTokenParams{ProjectID: projectID, Provider: provider.Name,
EncryptedToken: encodedToken, OwnerFilter: owner})

if err != nil {
if db.ErrIsUniqueViolation(err) {
return nil, util.UserVisibleError(codes.AlreadyExists, "token already exists")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "error storing access token: %v", err)
}
return &pb.StoreProviderTokenResponse{}, nil
Expand Down
5 changes: 4 additions & 1 deletion internal/controlplane/handlers_profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,10 @@ func (s *Server) CreateProfile(ctx context.Context,

// Create profile
profile, err := qtx.CreateProfile(ctx, params)
if err != nil {
if db.ErrIsUniqueViolation(err) {
log.Printf("profile already exists: %v", err)
return nil, util.UserVisibleError(codes.AlreadyExists, "profile already exists")
} else if err != nil {
log.Printf("error creating profile: %v", err)
return nil, status.Errorf(codes.Internal, "error creating profile")
}
Expand Down
34 changes: 34 additions & 0 deletions internal/db/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2023 Stacklok, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package db

import (
"errors"

"github.com/lib/pq"
)

// ErrIsUniqueViolation returns true if the error is a unique violation
func ErrIsUniqueViolation(err error) bool {
return isPostgresError(err, "23505")
}

func isPostgresError(err error, code string) bool {
var pgErr *pq.Error
if errors.As(err, &pgErr) {
return pgErr.Code == pq.ErrorCode(code)
}
return false
}

0 comments on commit a449e5b

Please sign in to comment.