~xenrox/10man-api

c55b1fa7e4548bc579decd84752bade76c6a30f7 — Thorben Günther 10 months ago 4732ed3
Add custom error handling

Will enable clients to better handle different errors.
2 files changed, 21 insertions(+), 1 deletions(-)

A database/error.go
M graph/schema.resolvers.go
A database/error.go => database/error.go +20 -0
@@ 0,0 1,20 @@
package database

import (
	"errors"

	"github.com/lib/pq"
)

// CheckErrorCode returns - depending on the postgres error code - a custom error
// that can be easier parsed and handled
func CheckErrorCode(err error) error {
	// https://www.postgresql.org/docs/current/errcodes-appendix.html
	if err, ok := err.(*pq.Error); ok {
		// duplicate key value violates unique constraint: 23505 unique_violation
		if err.Code == "23505" {
			return errors.New("NotUnique")
		}
	}
	return err
}

M graph/schema.resolvers.go => graph/schema.resolvers.go +1 -1
@@ 61,7 61,7 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.NewUser) 
	_, err = database.DB.Exec(query, input.SteamID, input.TeamspeakID, elo.Elo,
		isAdmin, input.Avatar, input.Name)
	if err != nil {
		return "", err
		return "", database.CheckErrorCode(err)
	}

	return "Created", nil