server/util/errors.go
2025-06-04 19:14:58 +02:00

70 lines
1.4 KiB
Go

package util
import "net/http"
type ChatErrorCode int
// List off all known error codes
const (
// internalServerError
GENERAL_ERROR ChatErrorCode = iota
DATABASE_CONNECTION_FAULT
DATABASE_QUERY_FAULT
// statusOk
USER_NOT_FOUND
WRONG_PASSWORD
USERNAME_TOO_SHORT
PASSWORD_TOO_SHORT
PASSWORDS_DONT_MATCH
)
var codeToMessage = map[ChatErrorCode]string{}
type ChatError struct {
Message string
Code ChatErrorCode
}
// Error returns the original errors message if not empty, else returns ErrorFromCode()
func (e ChatError) Error() string {
if e.Message != "" {
return e.Message
} else {
return e.ErrorFromCode()
}
}
// ErrorFromCode returns a string that is safe to show in API responses
func (e *ChatError) ErrorFromCode() string {
message, ok := codeToMessage[e.Code]
if ok {
return message
} else {
return "unknown error code"
}
}
// Status returns the http status of the error type
func (e *ChatError) Status() int {
switch e.Code {
case USER_NOT_FOUND:
case WRONG_PASSWORD:
case USERNAME_TOO_SHORT:
case PASSWORD_TOO_SHORT:
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
func MakeError(err error, code ChatErrorCode) *ChatError {
if err == nil {
return nil
}
return &ChatError{Message: err.Error(), Code: code}
}