Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Improve error handling
天舟b2214dfa40f0
diff --git a/backend/error.go b/backend/error.goindex db79d607a5..b0a6fb5509 100644--- a/backend/error.go+++ b/backend/error.go@@ -36,7 +36,7 @@ type Error struct {// Error implements the error interface. Not used by the application otherwise.func (e *Error) Error() string {- return fmt.Sprintf("wtf error: code=%s message=%s", e.Code, e.Message)+ return fmt.Sprintf("bytebase error: code=%s message=%s", e.Code, e.Message)}// ErrorCode unwraps an application error and returns its code.diff --git a/backend/server/auth.go b/backend/server/auth.goindex 91586b9e23..473bf6090b 100644--- a/backend/server/auth.go+++ b/backend/server/auth.go@@ -15,32 +15,32 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {g.POST("/auth/login", func(c echo.Context) error {login := &api.Login{}if err := jsonapi.UnmarshalPayload(c.Request().Body, login); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted login request.")+ return echo.NewHTTPError(http.StatusBadRequest, "malformatted login request").SetInternal(err)}user, err := s.PrincipalService.FindPrincipalByEmail(context.Background(), login.Email)if err != nil {if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {- return echo.NewHTTPError(http.StatusUnauthorized)+ return echo.NewHTTPError(http.StatusUnauthorized).SetInternal(err)}- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to authenticate user.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to authenticate user").SetInternal(err)}// Compare the stored hashed password, with the hashed version of the password that was received.if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(login.Password)); err != nil {// If the two passwords don't match, return a 401 status.- return echo.NewHTTPError(http.StatusUnauthorized, "Password is incorrect.")+ return echo.NewHTTPError(http.StatusUnauthorized, "incorrect password").SetInternal(err)}// If password is correct, generate tokens and set cookies.if err := GenerateTokensAndSetCookies(user, c); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate access token").SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)c.Response().WriteHeader(http.StatusOK)if err := jsonapi.MarshalPayload(c.Response().Writer, user); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal login response.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to marshal login response").SetInternal(err)}return nil@@ -49,12 +49,12 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {g.POST("/auth/signup", func(c echo.Context) error {signup := &api.Signup{}if err := jsonapi.UnmarshalPayload(c.Request().Body, signup); err != nil {- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted signup request.")+ return echo.NewHTTPError(http.StatusBadRequest, "malformatted signup request").SetInternal(err)}passwordHash, err := bcrypt.GenerateFromPassword([]byte(signup.Password), bcrypt.DefaultCost)if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate password hash.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate password hash").SetInternal(err)}principalCreate := &api.PrincipalCreate{@@ -69,19 +69,19 @@ func (s *Server) registerAuthRoutes(g *echo.Group) {user, err := s.PrincipalService.CreatePrincipal(context.Background(), principalCreate)if err != nil {if bytebase.ErrorCode(err) == bytebase.ECONFLICT {- return echo.NewHTTPError(http.StatusConflict)+ return echo.NewHTTPError(http.StatusConflict).SetInternal(err)}- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to signup user.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to signup user").SetInternal(err)}if err := GenerateTokensAndSetCookies(user, c); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to generate access token.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to generate access token").SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)c.Response().WriteHeader(http.StatusOK)if err := jsonapi.MarshalPayload(c.Response().Writer, user); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal signup response.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to marshal signup response").SetInternal(err)}return nildiff --git a/backend/server/jwt.go b/backend/server/jwt.goindex 08f2d979ff..936d7b0fda 100644--- a/backend/server/jwt.go+++ b/backend/server/jwt.go@@ -62,7 +62,7 @@ type Claims struct {func GenerateTokensAndSetCookies(user *api.Principal, c echo.Context) error {accessToken, err := generateAccessToken(user)if err != nil {- return err+ return fmt.Errorf("failed to generate access token: %w", err)}cookieExp := time.Now().Add(cookieExpDuration)@@ -72,7 +72,7 @@ func GenerateTokensAndSetCookies(user *api.Principal, c echo.Context) error {// We generate here a new refresh token and saving it to the cookie.refreshToken, err := generateRefreshToken(user)if err != nil {- return err+ return fmt.Errorf("failed to generate refresh token: %w", err)}setTokenCookie(refreshTokenCookieName, refreshToken, cookieExp, c)@@ -195,5 +195,5 @@ func TokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {// JWTErrorChecker will be executed when user try to access a protected path.func JWTErrorChecker(err error, c echo.Context) error {log.Printf("Unauthorized to access protected route %s, err: %v\n", c.Path(), err)- return err+ return fmt.Errorf("invalid access token: %w", err)}diff --git a/backend/server/principal.go b/backend/server/principal.goindex c3e4310296..4b24723b83 100644--- a/backend/server/principal.go+++ b/backend/server/principal.go@@ -17,13 +17,13 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {g.GET("/principal", func(c echo.Context) error {list, err := s.PrincipalService.FindPrincipalList(context.Background())if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed fetch principal list.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to fetch principal list").SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)c.Response().WriteHeader(http.StatusOK)if err := jsonapi.MarshalPayload(c.Response().Writer, list); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal principal list.")+ return echo.NewHTTPError(http.StatusInternalServerError, "failed to marshal principal list response").SetInternal(err)}return nil@@ -32,21 +32,21 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {g.GET("/principal/:id", func(c echo.Context) error {id, err := strconv.Atoi(c.Param("id"))if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s.", c.Param("id")))+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)}principal, err := s.PrincipalService.FindPrincipalByID(context.Background(), id)if err != nil {if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to find principal with ID: %v", id))+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("failed to find principal ID: %v", id)).SetInternal(err)}- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch principal.")+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to fetch principal ID: %v", id)).SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)c.Response().WriteHeader(http.StatusOK)if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal principal.")+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to marshal principal ID response: %v", id)).SetInternal(err)}return nil@@ -55,27 +55,27 @@ func (s *Server) registerPrincipalRoutes(g *echo.Group) {g.PATCH("/principal/:id", func(c echo.Context) error {id, err := strconv.Atoi(c.Param("id"))if err != nil {- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s.", c.Param("id")))+ return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("id"))).SetInternal(err)}principalPatch := &api.PrincipalPatch{UpdaterId: c.Get(GetPrincipalIdContextKey()).(int)}if err := jsonapi.UnmarshalPayload(c.Request().Body, principalPatch); err != nil {log.Println(err)- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch principal request.")+ return echo.NewHTTPError(http.StatusBadRequest, "malformatted patch principal request").SetInternal(err)}principal, err := s.PrincipalService.PatchPrincipalByID(context.Background(), id, principalPatch)if err != nil {if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Failed to find principal with ID: %v", id))+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("failed to find principal ID: %v", id)).SetInternal(err)}- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch principal.")+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to patch principal ID: %v", id)).SetInternal(err)}c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)c.Response().WriteHeader(http.StatusOK)if err := jsonapi.MarshalPayload(c.Response().Writer, principal); err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal principal.")+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to marshal principal ID response: %v", id)).SetInternal(err)}return nildiff --git a/backend/sqlite/principal.go b/backend/sqlite/principal.goindex a2b8f47359..648aa44f5f 100644--- a/backend/sqlite/principal.go+++ b/backend/sqlite/principal.go@@ -26,7 +26,7 @@ func NewPrincipalService(db *DB) *PrincipalService {func (s *PrincipalService) CreatePrincipal(ctx context.Context, create *api.PrincipalCreate) (*api.Principal, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {- return nil, err+ return nil, FormatError(err)}defer tx.Rollback()@@ -36,7 +36,7 @@ func (s *PrincipalService) CreatePrincipal(ctx context.Context, create *api.Prin}if err := tx.Commit(); err != nil {- return nil, err+ return nil, FormatError(err)}return principal, nil@@ -47,7 +47,7 @@ func (s *PrincipalService) CreatePrincipal(ctx context.Context, create *api.Prinfunc (s *PrincipalService) FindPrincipalByEmail(ctx context.Context, email string) (*api.Principal, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {- return nil, err+ return nil, FormatError(err)}defer tx.Rollback()@@ -55,7 +55,7 @@ func (s *PrincipalService) FindPrincipalByEmail(ctx context.Context, email strinif err != nil {return nil, err} else if len(list) == 0 {- return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: "Principal not found."}+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: "principal not found."}}return list[0], nil}@@ -65,7 +65,7 @@ func (s *PrincipalService) FindPrincipalByEmail(ctx context.Context, email strinfunc (s *PrincipalService) FindPrincipalByID(ctx context.Context, id int) (*api.Principal, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {- return nil, err+ return nil, FormatError(err)}defer tx.Rollback()@@ -76,7 +76,7 @@ func (s *PrincipalService) FindPrincipalByID(ctx context.Context, id int) (*api.func (s *PrincipalService) FindPrincipalList(ctx context.Context) ([]*api.Principal, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {- return nil, err+ return nil, FormatError(err)}defer tx.Rollback()@@ -93,17 +93,17 @@ func (s *PrincipalService) FindPrincipalList(ctx context.Context) ([]*api.Princifunc (s *PrincipalService) PatchPrincipalByID(ctx context.Context, id int, patch *api.PrincipalPatch) (*api.Principal, error) {tx, err := s.db.BeginTx(ctx, nil)if err != nil {- return nil, err+ return nil, FormatError(err)}defer tx.Rollback()principal, err := patchPrincipal(ctx, tx, id, patch)if err != nil {- return nil, err+ return nil, FormatError(err)}if err := tx.Commit(); err != nil {- return nil, err+ return nil, FormatError(err)}return principal, nil@@ -232,7 +232,7 @@ func findPrincipalByID(ctx context.Context, tx *Tx, id int) (*api.Principal, errif err != nil {return nil, err} else if len(list) == 0 {- return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: "Principal not found."}+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: "principal not found."}}return list[0], nil}@@ -281,5 +281,5 @@ func patchPrincipal(ctx context.Context, tx *Tx, id int, patch *api.PrincipalPatreturn &principal, nil}- return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: "Principal not found."}+ return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: "principal not found."}}diff --git a/backend/sqlite/sqlite.go b/backend/sqlite/sqlite.goindex dd80eceaf9..e2247ff797 100644--- a/backend/sqlite/sqlite.go+++ b/backend/sqlite/sqlite.go@@ -156,7 +156,6 @@ func (db *DB) migrate() error {v1, dirty1, err := m.Version()if err != nil {if err != migrate.ErrNilVersion {- log.Fatal(err)return err}}@@ -166,8 +165,7 @@ func (db *DB) migrate() error {if err == migrate.ErrNoChange {log.Println("No need to migrate down.")} else {- log.Fatal(err)- return err+ return fmt.Errorf("migrate down error: %w", err)}}@@ -175,7 +173,6 @@ func (db *DB) migrate() error {log.Printf("Database version before migration up: %v, dirty: %v", v2, dirty2)if err != nil {if err != migrate.ErrNilVersion {- log.Fatal(err)return err}}@@ -184,15 +181,13 @@ func (db *DB) migrate() error {if err == migrate.ErrNoChange {log.Println("No need to migrate up.")} else {- log.Fatal(err)- return err+ return fmt.Errorf("migrate up error: %w", err)}}v3, dirty3, err := m.Version()if err != nil {if err != migrate.ErrNilVersion {- log.Fatal(err)return err}}