39 lines
772 B
Go
39 lines
772 B
Go
package management
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
)
|
|
|
|
type AppError struct {
|
|
Status int
|
|
Code string
|
|
Message string
|
|
Fields map[string]any
|
|
}
|
|
|
|
func newAppError(status int, code, message string, fields map[string]any) *AppError {
|
|
return &AppError{Status: status, Code: code, Message: message, Fields: fields}
|
|
}
|
|
|
|
func (e *AppError) Error() string {
|
|
if e == nil {
|
|
return ""
|
|
}
|
|
return fmt.Sprintf("%s: %s", e.Code, e.Message)
|
|
}
|
|
|
|
func asAppError(err error) *AppError {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
if appErr, ok := err.(*AppError); ok {
|
|
return appErr
|
|
}
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return newAppError(404, "RESOURCE_NOT_FOUND", "resource does not exist", nil)
|
|
}
|
|
return newAppError(500, "INTERNAL_ERROR", "internal server error", nil)
|
|
}
|