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() { 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) err = rows.StructScan(&user)

View File

@ -5,12 +5,14 @@ import "net/http"
type ChatErrorCode int type ChatErrorCode int
// List off all known error codes // List off all known error codes
const ( const (
// internalServerError // GENERAL_ERROR for not classified system errros
GENERAL_ERROR ChatErrorCode = iota GENERAL_ERROR ChatErrorCode = iota
DATABASE_CONNECTION_FAULT DATABASE_CONNECTION_FAULT
DATABASE_QUERY_FAULT DATABASE_QUERY_FAULT
// statusOk
USER_NOT_FOUND USER_NOT_FOUND
WRONG_PASSWORD WRONG_PASSWORD
USERNAME_TOO_SHORT USERNAME_TOO_SHORT
@ -18,7 +20,16 @@ const (
PASSWORDS_DONT_MATCH 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 { type ChatError struct {
Message string Message string
@ -48,15 +59,18 @@ func (e *ChatError) ErrorFromCode() string {
func (e *ChatError) Status() int { func (e *ChatError) Status() int {
switch e.Code { switch e.Code {
case USER_NOT_FOUND: case USER_NOT_FOUND:
fallthrough
case WRONG_PASSWORD: case WRONG_PASSWORD:
fallthrough
case USERNAME_TOO_SHORT: case USERNAME_TOO_SHORT:
fallthrough
case PASSWORD_TOO_SHORT: case PASSWORD_TOO_SHORT:
fallthrough
case PASSWORDS_DONT_MATCH: case PASSWORDS_DONT_MATCH:
return http.StatusOK return http.StatusOK
default: default:
return http.StatusInternalServerError return http.StatusInternalServerError
} }
return http.StatusInternalServerError
} }
// MakeError makes an error with the given code id err exists // MakeError makes an error with the given code id err exists