Refactor error handling in UserDAO and update error codes in util package

This commit is contained in:
BENEDEK László 2025-06-04 19:26:46 +02:00
parent 4854d926d7
commit de83676794
2 changed files with 19 additions and 5 deletions

View File

@ -31,7 +31,7 @@ func (d UserDAOPG) Read(user model.User) (model.User, *util.ChatError) {
}
if !rows.Next() {
return user, util.MakeError(err, util.USER_NOT_FOUND)
return user, &util.ChatError{Message: "", Code: util.USER_NOT_FOUND}
}
err = rows.StructScan(&user)

View File

@ -5,12 +5,14 @@ import "net/http"
type ChatErrorCode int
// List off all known error codes
const (
// internalServerError
// GENERAL_ERROR for not classified system errros
GENERAL_ERROR ChatErrorCode = iota
DATABASE_CONNECTION_FAULT
DATABASE_QUERY_FAULT
// statusOk
USER_NOT_FOUND
WRONG_PASSWORD
USERNAME_TOO_SHORT
@ -18,7 +20,16 @@ const (
PASSWORDS_DONT_MATCH
)
var codeToMessage = map[ChatErrorCode]string{}
var codeToMessage = map[ChatErrorCode]string{
GENERAL_ERROR: "an unexpected error occurred",
DATABASE_CONNECTION_FAULT: "database connection failed",
DATABASE_QUERY_FAULT: "database query failed",
USER_NOT_FOUND: "user not found",
WRONG_PASSWORD: "incorrect password",
USERNAME_TOO_SHORT: "username is too short",
PASSWORD_TOO_SHORT: "password is too short",
PASSWORDS_DONT_MATCH: "passwords do not match",
}
type ChatError struct {
Message string
@ -48,15 +59,18 @@ func (e *ChatError) ErrorFromCode() string {
func (e *ChatError) Status() int {
switch e.Code {
case USER_NOT_FOUND:
fallthrough
case WRONG_PASSWORD:
fallthrough
case USERNAME_TOO_SHORT:
fallthrough
case PASSWORD_TOO_SHORT:
fallthrough
case PASSWORDS_DONT_MATCH:
return http.StatusOK
default:
return http.StatusInternalServerError
}
return http.StatusInternalServerError
}
// MakeError makes an error with the given code id err exists