This commit is contained in:
jdl
2026-06-13 14:46:55 +02:00
parent 3dcd1c1080
commit 76fce15e32
2 changed files with 90 additions and 0 deletions

33
hub/errs/db.go Normal file
View File

@@ -0,0 +1,33 @@
package errs
import (
"database/sql"
"errors"
"log"
sqlite3 "github.com/mattn/go-sqlite3"
)
func DB(err error) error {
if err == nil {
return nil
}
if _, ok := err.(*Error); ok {
return err
}
if err == sql.ErrNoRows {
return ErrNotFound
}
var se sqlite3.Error
if errors.As(err, &se) {
switch se.ExtendedCode {
case sqlite3.ErrConstraintUnique, sqlite3.ErrConstraintPrimaryKey:
return ErrAlreadyExists
}
}
log.Printf("Unexpected error: %v", err)
return ErrUnexpected
}

57
hub/errs/types.go Normal file
View File

@@ -0,0 +1,57 @@
package errs
import (
"fmt"
"net/http"
)
type Error struct {
Code int
Msg string
}
func (e *Error) Error() string {
return fmt.Sprintf("[%d] %s", e.Code, e.Msg)
}
var (
ErrUnexpected = Internal.WithMsg("Unexpected internal error.")
ErrNotFound = NotFound.WithMsg("Not found.")
ErrAlreadyExists = Conflict.WithMsg("AlreadyExists.")
// Validation errors.
ErrInvalidIP = BadRequest.WithMsg("Invalid IP.")
ErrInvalidPeerIP = BadRequest.WithMsg("Invalid peer IP.")
ErrNonPrivateIP = BadRequest.WithMsg("Non-private IP.")
ErrInvalidPort = BadRequest.WithMsg("Invalid port.")
ErrInvalidNetName = BadRequest.WithMsg("Invalid network name.")
ErrNetNameNotLocal = BadRequest.WithMsg("Network name must end with .local.")
ErrInvalidPeerName = BadRequest.WithMsg("Invalid peer name.")
)
// ----------------------------------------------------------------------------
type Type struct {
Code int
Msg string
}
func (t Type) WithErr(err error) *Error {
return &Error{Code: t.Code, Msg: err.Error()}
}
func (t Type) WithMsg(msg string) *Error {
return &Error{Code: t.Code, Msg: msg}
}
func (t Type) WithMsgf(msg string, args ...any) *Error {
return &Error{Code: t.Code, Msg: fmt.Sprintf(msg, args...)}
}
var (
Internal = Type{Code: http.StatusInternalServerError}
NotAuthorized = Type{Code: http.StatusUnauthorized}
NotFound = Type{Code: http.StatusNotFound}
BadRequest = Type{Code: http.StatusBadRequest}
Conflict = Type{Code: http.StatusConflict}
)