Skip to content

Commit

Permalink
Update uses of errors.Error
Browse files Browse the repository at this point in the history
  • Loading branch information
System-Glitch committed Jan 25, 2024
1 parent a3b5ea0 commit 17bf097
Show file tree
Hide file tree
Showing 23 changed files with 96 additions and 116 deletions.
9 changes: 2 additions & 7 deletions auth/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,7 @@ func (s *JWTService) GenerateTokenWithClaims(claims jwt.MapClaims, signingMethod
return "", err
}
result, err := token.SignedString(key)
if err != nil {
err = errorutil.New(err)
}
return result, err
return result, errorutil.New(err)
}

// GetKey load a JWT signature key from the config.
Expand Down Expand Up @@ -159,10 +156,8 @@ func (s *JWTService) GetKey(entry string) (any, error) {

if err == nil {
s.cache.Store(entry, key)
} else {
err = errorutil.New(err)
}
return key, err
return key, errorutil.New(err)
}

// GetPrivateKey loads the private key that corresponds to the given `signingMethod`.
Expand Down
30 changes: 14 additions & 16 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (l *loader) register(key string, entry Entry) {
category, entryKey, exists := walk(l.defaults, key)
if exists {
if !reflect.DeepEqual(&entry, category[entryKey].(*Entry)) {
panic(errors.New(fmt.Errorf("attempted to override registered config entry %q", key)))
panic(errors.Errorf("attempted to override registered config entry %q", key))
}
} else {
category[entryKey] = &entry
Expand Down Expand Up @@ -188,10 +188,8 @@ func (l *loader) readConfigFile(filesystem fs.FS, file string) (o object, err er
}
}()
jsonParser := json.NewDecoder(configFile)
err = jsonParser.Decode(&o)
}

if err != nil {
err = errors.New(jsonParser.Decode(&o))
} else {
err = errors.New(err)
}

Expand Down Expand Up @@ -243,7 +241,7 @@ func walk(currentCategory object, key string) (object, string, bool) {
currentCategory = category
} else {
if dotIndex < len(key) {
panic(errors.New(fmt.Errorf("attempted to add an entry to non-category %q", key[:dotIndex])))
panic(errors.Errorf("attempted to add an entry to non-category %q", key[:dotIndex]))
}

// Entry exists
Expand All @@ -263,7 +261,7 @@ func walk(currentCategory object, key string) (object, string, bool) {
}
}

panic(errors.New(fmt.Errorf("attempted to replace the %q category with an entry", key)))
panic(errors.Errorf("attempted to replace the %q category with an entry", key))
}

// createMissingCategories based on the key path, starting at the given index.
Expand Down Expand Up @@ -355,7 +353,7 @@ func (c *Config) Get(key string) any {
return val
}

panic(errors.New(fmt.Errorf("config entry \"%s\" doesn't exist", key)))
panic(errors.Errorf("config entry \"%s\" doesn't exist", key))
}

func (c *Config) get(key string) (any, bool) {
Expand Down Expand Up @@ -396,7 +394,7 @@ func (c *Config) get(key string) (any, bool) {
func (c *Config) GetString(key string) string {
str, ok := c.Get(key).(string)
if !ok {
panic(errors.New(fmt.Errorf("config entry \"%s\" is not a string", key)))
panic(errors.Errorf("config entry \"%s\" is not a string", key))
}
return str
}
Expand All @@ -406,7 +404,7 @@ func (c *Config) GetString(key string) string {
func (c *Config) GetBool(key string) bool {
val, ok := c.Get(key).(bool)
if !ok {
panic(errors.New(fmt.Errorf("config entry \"%s\" is not a bool", key)))
panic(errors.Errorf("config entry \"%s\" is not a bool", key))
}
return val
}
Expand All @@ -416,7 +414,7 @@ func (c *Config) GetBool(key string) bool {
func (c *Config) GetInt(key string) int {
val, ok := c.Get(key).(int)
if !ok {
panic(errors.New(fmt.Errorf("config entry \"%s\" is not an int", key)))
panic(errors.Errorf("config entry \"%s\" is not an int", key))
}
return val
}
Expand All @@ -426,7 +424,7 @@ func (c *Config) GetInt(key string) int {
func (c *Config) GetFloat(key string) float64 {
val, ok := c.Get(key).(float64)
if !ok {
panic(errors.New(fmt.Errorf("config entry \"%s\" is not a float64", key)))
panic(errors.Errorf("config entry \"%s\" is not a float64", key))
}
return val
}
Expand All @@ -436,7 +434,7 @@ func (c *Config) GetFloat(key string) float64 {
func (c *Config) GetStringSlice(key string) []string {
str, ok := c.Get(key).([]string)
if !ok {
panic(errors.New(fmt.Errorf("config entry \"%s\" is not a string slice", key)))
panic(errors.Errorf("config entry \"%s\" is not a string slice", key))
}
return str
}
Expand All @@ -446,7 +444,7 @@ func (c *Config) GetStringSlice(key string) []string {
func (c *Config) GetBoolSlice(key string) []bool {
str, ok := c.Get(key).([]bool)
if !ok {
panic(errors.New(fmt.Errorf("config entry \"%s\" is not a bool slice", key)))
panic(errors.Errorf("config entry \"%s\" is not a bool slice", key))
}
return str
}
Expand All @@ -456,7 +454,7 @@ func (c *Config) GetBoolSlice(key string) []bool {
func (c *Config) GetIntSlice(key string) []int {
str, ok := c.Get(key).([]int)
if !ok {
panic(errors.New(fmt.Errorf("config entry \"%s\" is not an int slice", key)))
panic(errors.Errorf("config entry \"%s\" is not an int slice", key))
}
return str
}
Expand All @@ -466,7 +464,7 @@ func (c *Config) GetIntSlice(key string) []int {
func (c *Config) GetFloatSlice(key string) []float64 {
str, ok := c.Get(key).([]float64)
if !ok {
panic(errors.New(fmt.Errorf("config entry \"%s\" is not a float64 slice", key)))
panic(errors.Errorf("config entry \"%s\" is not a float64 slice", key))
}
return str
}
Expand Down
17 changes: 8 additions & 9 deletions config/entry.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package config

import (
"fmt"
"os"
"reflect"
"strconv"
Expand Down Expand Up @@ -54,7 +53,7 @@ func (e *Entry) validate(key string) error {
message = "%q type must be %s"
}

return errors.New(fmt.Errorf(message, key, e.Type))
return errors.Errorf(message, key, e.Type)
}

if len(e.AuthorizedValues) > 0 {
Expand All @@ -65,11 +64,11 @@ func (e *Entry) validate(key string) error {
length := list.Len()
for i := 0; i < length; i++ {
if !lo.Contains(e.AuthorizedValues, list.Index(i).Interface()) {
return errors.New(fmt.Errorf("%q elements must have one of the following values: %v", key, e.AuthorizedValues))
return errors.Errorf("%q elements must have one of the following values: %v", key, e.AuthorizedValues)
}
}
} else if !lo.Contains(e.AuthorizedValues, e.Value) {
return errors.New(fmt.Errorf("%q must have one of the following values: %v", key, e.AuthorizedValues))
return errors.Errorf("%q must have one of the following values: %v", key, e.AuthorizedValues)
}
}

Expand Down Expand Up @@ -150,7 +149,7 @@ func (e *Entry) tryEnvVarConversion(key string) error {
if err == nil && val != nil {

if e.IsSlice {
return errors.New(fmt.Errorf("%q is a slice entry, it cannot be loaded from env", key))
return errors.Errorf("%q is a slice entry, it cannot be loaded from env", key)
}

e.Value = val
Expand All @@ -166,25 +165,25 @@ func (e *Entry) convertEnvVar(str, key string) (any, error) {
varName := str[2 : len(str)-1]
value, set := os.LookupEnv(varName)
if !set {
return nil, errors.New(fmt.Errorf("%q: %q environment variable is not set", key, varName))
return nil, errors.Errorf("%q: %q environment variable is not set", key, varName)
}

switch e.Type {
case reflect.Int:
if i, err := strconv.Atoi(value); err == nil {
return i, nil
}
return nil, errors.New(fmt.Errorf("%q could not be converted to int from environment variable %q of value %q", key, varName, value))
return nil, errors.Errorf("%q could not be converted to int from environment variable %q of value %q", key, varName, value)
case reflect.Float64:
if f, err := strconv.ParseFloat(value, 64); err == nil {
return f, nil
}
return nil, errors.New(fmt.Errorf("%q could not be converted to float64 from environment variable %q of value %q", key, varName, value))
return nil, errors.Errorf("%q could not be converted to float64 from environment variable %q of value %q", key, varName, value)
case reflect.Bool:
if b, err := strconv.ParseBool(value); err == nil {
return b, nil
}
return nil, errors.New(fmt.Errorf("%q could not be converted to bool from environment variable %q of value %q", key, varName, value))
return nil, errors.Errorf("%q could not be converted to bool from environment variable %q of value %q", key, varName, value)
default:
// Keep value as string if type is not supported and let validation do its job
return value, nil
Expand Down
7 changes: 3 additions & 4 deletions database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package database

import (
"errors"
"fmt"
"time"

"gorm.io/gorm"
Expand All @@ -27,12 +26,12 @@ func New(cfg *config.Config, logger func() *slog.Logger) (*gorm.DB, error) {
driver := cfg.GetString("database.connection")

if driver == "none" {
return nil, fmt.Errorf("Cannot create DB connection. Database is set to \"none\" in the config")
return nil, errorutil.Errorf("Cannot create DB connection. Database is set to \"none\" in the config")
}

dialect, ok := dialects[driver]
if !ok {
return nil, fmt.Errorf("DB Connection %q not supported, forgotten import?", driver)
return nil, errorutil.Errorf("DB Connection %q not supported, forgotten import?", driver)
}

dsn := dialect.buildDSN(cfg)
Expand Down Expand Up @@ -90,7 +89,7 @@ func initTimeoutPlugin(cfg *config.Config, db *gorm.DB) error {
ReadTimeout: time.Duration(cfg.GetInt("database.defaultReadQueryTimeout")) * time.Millisecond,
WriteTimeout: time.Duration(cfg.GetInt("database.defaultWriteQueryTimeout")) * time.Millisecond,
}
return db.Use(timeoutPlugin)
return errorutil.New(db.Use(timeoutPlugin))
}

func initSQLDB(cfg *config.Config, db *gorm.DB) {
Expand Down
3 changes: 1 addition & 2 deletions database/dialect.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package database

import (
"fmt"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -64,7 +63,7 @@ func RegisterDialect(name, template string, initializer DialectorInitializer) {
mu.Lock()
defer mu.Unlock()
if _, ok := dialects[name]; ok {
panic(errors.New(fmt.Errorf("dialect %q already exists", name)))
panic(errors.Errorf("dialect %q already exists", name))
}
dialects[name] = dialect{initializer, template}
}
3 changes: 1 addition & 2 deletions lang/lang.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package lang

import (
"encoding/json"
"fmt"
"strings"

"github.com/samber/lo"
Expand Down Expand Up @@ -86,7 +85,7 @@ func (l *Languages) Load(fs fsutil.FS, language, path string) error {
return l.load(fs, language, path)
}

return errors.New(fmt.Errorf("failed loading language \"%s\", directory \"%s\" doesn't exist or is not readable", language, path))
return errors.Errorf("failed loading language \"%s\", directory \"%s\" doesn't exist or is not readable", language, path)
}

func (l *Languages) load(fs fsutil.FS, lang string, path string) error {
Expand Down
5 changes: 1 addition & 4 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,7 @@ func (w *Writer) PreWrite(b []byte) {
func (w *Writer) Write(b []byte) (int, error) {
w.length += len(b)
n, err := w.writer.Write(b)
if err != nil {
err = errors.New(err)
}
return n, err
return n, errors.New(err)
}

// Close the writer and its child ResponseWriter, flushing response
Expand Down
9 changes: 3 additions & 6 deletions middleware/compress/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,14 @@ func (w *compressWriter) PreWrite(b []byte) {

func (w *compressWriter) Write(b []byte) (int, error) {
n, err := w.WriteCloser.Write(b)
if err != nil {
err = errors.New(err)
}
return n, err
return n, errors.New(err)
}

func (w *compressWriter) Close() error {
err := w.WriteCloser.Close()
err := errors.New(w.WriteCloser.Close())

if wr, ok := w.childWriter.(io.Closer); ok {
return wr.Close()
return errors.New(wr.Close())
}

return err
Expand Down
11 changes: 3 additions & 8 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,7 @@ func (r *Response) PreWrite(b []byte) {
func (r *Response) Write(data []byte) (int, error) {
r.PreWrite(data)
n, err := r.writer.Write(data)
if err != nil {
err = errorutil.New(err)
}
return n, err
return n, errorutil.New(err)
}

// WriteHeader sends an HTTP response header with the provided
Expand Down Expand Up @@ -144,10 +141,8 @@ func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {
c, b, e := hijacker.Hijack()
if e == nil {
r.hijacked = true
} else {
e = errorutil.New(e)
}
return c, b, e
return c, b, errorutil.New(e)
}

// Hijacked returns true if the underlying connection has been successfully hijacked
Expand Down Expand Up @@ -177,7 +172,7 @@ func (r *Response) SetWriter(writer io.Writer) {

func (r *Response) close() error {
if wr, ok := r.writer.(io.Closer); ok {
return wr.Close()
return errorutil.New(wr.Close())
}
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion route.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ func (r *Route) BuildURI(parameters ...string) string {
fullURI, fullParameters := r.GetFullURIAndParameters()

if len(parameters) != len(fullParameters) {
panic(errors.New(fmt.Errorf("BuildURI: route has %d parameters, %d given", len(fullParameters), len(parameters))))
panic(errors.Errorf("BuildURI: route has %d parameters, %d given", len(fullParameters), len(parameters)))
}

var builder strings.Builder
Expand Down
6 changes: 1 addition & 5 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,9 +489,5 @@ func (r *Router) finalize(response *Response, request *Request) error {
response.WriteHeader(response.status)
}

err := response.close()
if err != nil {
return errorutil.New(err)
}
return nil
return errorutil.New(response.close())
}
8 changes: 2 additions & 6 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ func (s *Server) Service(name string) Service {
if s, ok := s.services[name]; ok {
return s
}
panic(errors.New(fmt.Errorf("service %q does not exist", name)))
panic(errors.Errorf("service %q does not exist", name))
}

// LookupService search for a service by its name. If the service
Expand Down Expand Up @@ -377,11 +377,7 @@ func (s *Server) CloseDB() error {
if err != nil {
return errors.New(err)
}
err = db.Close()
if err != nil {
err = errors.New(err)
}
return err
return errors.New(db.Close())
}

// Router returns the root router.
Expand Down
Loading

0 comments on commit 17bf097

Please sign in to comment.