93 lines
2.1 KiB
Go
93 lines
2.1 KiB
Go
package util
|
|
|
|
import "net/http"
|
|
|
|
type ChatErrorCode int
|
|
|
|
// List off all known error codes
|
|
|
|
const (
|
|
// GENERAL_ERROR for not classified system errros
|
|
GENERAL_ERROR ChatErrorCode = iota
|
|
|
|
DATABASE_CONNECTION_FAULT
|
|
DATABASE_QUERY_FAULT
|
|
|
|
NOT_FOUND
|
|
WRONG_PASSWORD
|
|
USERNAME_TOO_SHORT
|
|
PASSWORD_TOO_SHORT
|
|
PASSWORDS_DONT_MATCH
|
|
SEND_NOT_AUTHORIZED
|
|
READ_NOT_AUTHORIZED
|
|
|
|
NOT_LOGGED_IN
|
|
)
|
|
|
|
var codeToMessage = map[ChatErrorCode]string{
|
|
GENERAL_ERROR: "an unexpected error occurred",
|
|
DATABASE_CONNECTION_FAULT: "database connection failed",
|
|
DATABASE_QUERY_FAULT: "database query failed",
|
|
NOT_FOUND: "item 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",
|
|
SEND_NOT_AUTHORIZED: "not authorized to send messages in this channel",
|
|
READ_NOT_AUTHORIZED: "not authorized to read messages in this channel",
|
|
NOT_LOGGED_IN: "not logged in",
|
|
}
|
|
|
|
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 NOT_FOUND:
|
|
fallthrough
|
|
case WRONG_PASSWORD:
|
|
fallthrough
|
|
case USERNAME_TOO_SHORT:
|
|
fallthrough
|
|
case PASSWORD_TOO_SHORT:
|
|
fallthrough
|
|
case PASSWORDS_DONT_MATCH:
|
|
return http.StatusOK
|
|
case NOT_LOGGED_IN:
|
|
return http.StatusUnauthorized
|
|
default:
|
|
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}
|
|
}
|