From 5c103e8cd3cae331b45b04f0a75f14675c798cc7 Mon Sep 17 00:00:00 2001 From: Yang Luo Date: Thu, 14 Dec 2023 10:11:06 +0800 Subject: [PATCH] Improve error handling in GenerateIdForNewUser() --- object/user.go | 5 ++++- util/string.go | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/object/user.go b/object/user.go index f414df9b..34453742 100644 --- a/object/user.go +++ b/object/user.go @@ -1021,7 +1021,10 @@ func GenerateIdForNewUser(application *Application) (string, error) { lastUserId := -1 if lastUser != nil { - lastUserId = util.ParseInt(lastUser.Id) + lastUserId, err = util.ParseIntWithError(lastUser.Id) + if err != nil { + return util.GenerateId(), nil + } } res := strconv.Itoa(lastUserId + 1) diff --git a/util/string.go b/util/string.go index e49c3871..fe2d0b29 100644 --- a/util/string.go +++ b/util/string.go @@ -45,6 +45,19 @@ func ParseInt(s string) int { return i } +func ParseIntWithError(s string) (int, error) { + if s == "" { + return 0, fmt.Errorf("ParseIntWithError() error, empty string") + } + + i, err := strconv.Atoi(s) + if err != nil { + return 0, err + } + + return i, nil +} + func ParseFloat(s string) float64 { f, err := strconv.ParseFloat(s, 64) if err != nil {