Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

enhancement: wrap errors with meaningful messages (#332)

Guilherme Oenninge46b3f4d81a6
diff --git a/app/actions/idea.go b/app/actions/idea.go
index 1e8e69df3..d847c1362 100644
--- a/app/actions/idea.go
+++ b/app/actions/idea.go
@@ -7,6 +7,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -43,7 +44,7 @@ func (input *CreateNewIdea) Validate(user *models.User, services *app.Services)
}
idea, err := services.Ideas.GetBySlug(slug.Make(input.Model.Title))
- if err != nil && err != app.ErrNotFound {
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
} else if idea != nil {
result.AddFieldFailure("title", "This has already been posted before.")
@@ -91,7 +92,7 @@ func (input *UpdateIdea) Validate(user *models.User, services *app.Services) *va
}
another, err := services.Ideas.GetBySlug(slug.Make(input.Model.Title))
- if err != nil && err != app.ErrNotFound {
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
} else if another != nil && another.ID != idea.ID {
result.AddFieldFailure("title", "This has already been posted before.")
@@ -161,7 +162,7 @@ func (input *SetResponse) Validate(user *models.User, services *app.Services) *v
original, err := services.Ideas.GetByNumber(input.Model.OriginalNumber)
if err != nil {
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
result.AddFieldFailure("originalNumber", "Original idea not found")
} else {
return validate.Error(err)
diff --git a/app/actions/signin.go b/app/actions/signin.go
index b5c306714..2b51822c5 100644
--- a/app/actions/signin.go
+++ b/app/actions/signin.go
@@ -5,6 +5,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/uuid"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -80,7 +81,7 @@ func (input *CompleteProfile) Validate(user *models.User, services *app.Services
} else {
request, err := services.Tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, input.Model.Key)
if err != nil {
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
result.AddFieldFailure("key", "Key is invalid.")
} else {
return validate.Error(err)
diff --git a/app/actions/tag.go b/app/actions/tag.go
index 85be8a3ed..af87aa36a 100644
--- a/app/actions/tag.go
+++ b/app/actions/tag.go
@@ -5,6 +5,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/validate"
"github.com/gosimple/slug"
)
@@ -45,7 +46,7 @@ func (input *CreateEditTag) Validate(user *models.User, services *app.Services)
result.AddFieldFailure("name", "Name must be less than 30 characters.")
} else {
duplicateTag, err := services.Tags.GetBySlug(slug.Make(input.Model.Name))
- if err != nil && err != app.ErrNotFound {
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
} else if err == nil && (input.Tag == nil || input.Tag.ID != duplicateTag.ID) {
result.AddFieldFailure("name", "This tag name is already in use.")
diff --git a/app/actions/user.go b/app/actions/user.go
index 2a3fc1f16..5cf1c32ae 100644
--- a/app/actions/user.go
+++ b/app/actions/user.go
@@ -5,6 +5,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/uuid"
"github.com/getfider/fider/app/pkg/validate"
)
@@ -36,7 +37,7 @@ func (input *ChangeUserRole) Validate(user *models.User, services *app.Services)
}
target, err := services.Users.GetByID(input.Model.UserID)
if err != nil {
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
result.AddFieldFailure("user_id", "User not found")
} else {
return validate.Error(err)
@@ -90,7 +91,7 @@ func (input *ChangeUserEmail) Validate(user *models.User, services *app.Services
}
existing, err := services.Users.GetByEmail(input.Model.Email)
- if err != nil && err != app.ErrNotFound {
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
return validate.Error(err)
}
if err == nil && existing.ID != user.ID {
diff --git a/app/handlers/common.go b/app/handlers/common.go
index ebeb8b6b3..eb8d33642 100644
--- a/app/handlers/common.go
+++ b/app/handlers/common.go
@@ -7,6 +7,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/web"
)
@@ -42,7 +43,7 @@ func validateKey(kind models.EmailVerificationKind, c web.Context) (*models.Emai
result, err := c.Services().Tenants.FindVerificationByKey(kind, key)
if err != nil {
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
return nil, c.Redirect(http.StatusTemporaryRedirect, c.BaseURL())
}
return nil, c.Failure(err)
diff --git a/app/handlers/idea_test.go b/app/handlers/idea_test.go
index bd09a46a0..45039f705 100644
--- a/app/handlers/idea_test.go
+++ b/app/handlers/idea_test.go
@@ -9,6 +9,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/handlers"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/mock"
. "github.com/onsi/gomega"
)
@@ -442,5 +443,5 @@ func TestDeleteIdeaHandler_Authorized(t *testing.T) {
Expect(code).To(Equal(http.StatusOK))
idea, err := services.Ideas.GetByNumber(idea.Number)
Expect(idea).To(BeNil())
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
}
diff --git a/app/handlers/settings_test.go b/app/handlers/settings_test.go
index 7b7b32f74..269fc2d76 100644
--- a/app/handlers/settings_test.go
+++ b/app/handlers/settings_test.go
@@ -10,6 +10,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/handlers"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/mock"
. "github.com/onsi/gomega"
)
@@ -182,5 +183,5 @@ func TestVerifyChangeEmailKeyHandler_DifferentUser(t *testing.T) {
Expect(err).To(BeNil())
_, err = services.Users.GetByEmail("[email protected]")
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
}
diff --git a/app/handlers/signin.go b/app/handlers/signin.go
index 15a26645d..79c9ff6fd 100644
--- a/app/handlers/signin.go
+++ b/app/handlers/signin.go
@@ -12,6 +12,7 @@ import (
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/web"
"github.com/getfider/fider/app/tasks"
@@ -63,11 +64,11 @@ func OAuthCallback(provider string) web.HandlerFunc {
users := c.Services().Users
user, err := users.GetByProvider(provider, oauthUser.ID.String())
- if err == app.ErrNotFound && oauthUser.Email != "" {
+ if errors.Cause(err) == app.ErrNotFound && oauthUser.Email != "" {
user, err = users.GetByEmail(oauthUser.Email)
}
if err != nil {
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
user = &models.User{
Name: oauthUser.Name,
Tenant: tenant,
@@ -178,7 +179,7 @@ func VerifySignInKey(kind models.EmailVerificationKind) web.HandlerFunc {
} else if kind == models.EmailVerificationKindSignIn {
user, err = c.Services().Users.GetByEmail(result.Email)
if err != nil {
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
// This will render a page for /signin/verify URL using same variables as home page
return Index()(c)
}
@@ -211,7 +212,7 @@ func CompleteSignInProfile() web.HandlerFunc {
}
_, err := c.Services().Users.GetByEmail(input.Model.Email)
- if err != app.ErrNotFound {
+ if errors.Cause(err) != app.ErrNotFound {
return c.Ok(web.Map{})
}
diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go
index ca4edcf30..ec3db87f4 100644
--- a/app/handlers/signin_test.go
+++ b/app/handlers/signin_test.go
@@ -10,6 +10,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/handlers"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/oauth"
@@ -153,7 +154,7 @@ func TestCallbackHandler_ExistingUser_WithoutEmail(t *testing.T) {
Execute(handlers.OAuthCallback(oauth.FacebookProvider))
_, err := services.Users.GetByID(4)
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(code).To(Equal(http.StatusTemporaryRedirect))
Expect(response.Header().Get("Location")).To(Equal("http://demo.test.fider.io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyL2lkIjozLCJ1c2VyL25hbWUiOiJTb21lIEZhY2Vib29rIEd1eSIsInVzZXIvZW1haWwiOiIifQ.DBcMmKSrGxiXGVCq9QT716xfw3M4kzP-Njazsk6vaFI"))
diff --git a/app/handlers/signup.go b/app/handlers/signup.go
index fdbc50d58..624e65c47 100644
--- a/app/handlers/signup.go
+++ b/app/handlers/signup.go
@@ -12,6 +12,7 @@ import (
"github.com/getfider/fider/app/actions"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/pkg/web"
)
@@ -98,7 +99,7 @@ func SignUp() web.HandlerFunc {
return func(c web.Context) error {
if env.IsSingleHostMode() {
tenant, err := c.Services().Tenants.First()
- if err != nil && err != app.ErrNotFound {
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
return c.Failure(err)
}
diff --git a/app/handlers/signup_test.go b/app/handlers/signup_test.go
index e13002909..c69964ee5 100644
--- a/app/handlers/signup_test.go
+++ b/app/handlers/signup_test.go
@@ -8,6 +8,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/handlers"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/mock"
. "github.com/onsi/gomega"
@@ -135,6 +136,6 @@ func TestCreateTenantHandler_WithEmailAndName(t *testing.T) {
Expect(tenant.Status).To(Equal(models.TenantInactive))
user, err := services.Users.GetByEmail("[email protected]")
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(user).To(BeNil())
}
diff --git a/app/handlers/tag_test.go b/app/handlers/tag_test.go
index 2702ff62d..2f117bb7c 100644
--- a/app/handlers/tag_test.go
+++ b/app/handlers/tag_test.go
@@ -6,6 +6,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/handlers"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
. "github.com/onsi/gomega"
@@ -124,7 +125,7 @@ func TestEditExistingTagHandler(t *testing.T) {
Expect(status).To(Equal(http.StatusOK))
tag, err := services.Tags.GetBySlug("bug")
Expect(tag).To(BeNil())
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
tag, err = services.Tags.GetBySlug("feature-request")
Expect(tag).ToNot(BeNil())
@@ -156,7 +157,7 @@ func TestDeleteExistingTagHandler(t *testing.T) {
tag, err := services.Tags.GetBySlug("bug")
Expect(status).To(Equal(http.StatusOK))
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(tag).To(BeNil())
}
diff --git a/app/middlewares/domain.go b/app/middlewares/domain.go
index f964fd456..261a39222 100644
--- a/app/middlewares/domain.go
+++ b/app/middlewares/domain.go
@@ -8,6 +8,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/web"
)
@@ -25,7 +26,7 @@ func SingleTenant() web.MiddlewareFunc {
return func(c web.Context) error {
tenant, err := c.Services().Tenants.First()
if err != nil {
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
return c.Redirect(http.StatusTemporaryRedirect, "/signup")
}
return c.Failure(err)
@@ -56,7 +57,7 @@ func MultiTenant() web.MiddlewareFunc {
return next(c)
}
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
c.Logger().Debugf("Tenant not found for '%s'.", hostname)
return c.NotFound()
}
diff --git a/app/middlewares/jwt.go b/app/middlewares/jwt.go
index 91d188f3d..465cee698 100644
--- a/app/middlewares/jwt.go
+++ b/app/middlewares/jwt.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/web"
)
@@ -17,7 +18,7 @@ func JwtGetter() web.MiddlewareFunc {
cookie, err := c.Cookie(web.CookieAuthName)
if err != nil {
- if err == http.ErrNoCookie {
+ if errors.Cause(err) == http.ErrNoCookie {
return next(c)
}
return err
@@ -31,7 +32,7 @@ func JwtGetter() web.MiddlewareFunc {
user, err := c.Services().Users.GetByID(claims.UserID)
if err != nil {
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
c.RemoveCookie(web.CookieAuthName)
return next(c)
}
diff --git a/app/middlewares/setup.go b/app/middlewares/setup.go
index 56f4ecd4b..dde71c3a5 100644
--- a/app/middlewares/setup.go
+++ b/app/middlewares/setup.go
@@ -2,7 +2,6 @@ package middlewares
import (
"fmt"
- "runtime/debug"
"time"
"github.com/getfider/fider/app/pkg/log"
@@ -30,8 +29,13 @@ func WorkerSetup(logger log.Logger) worker.MiddlewareFunc {
emailer := app.NewEmailer(logger)
return func(next worker.Job) worker.Job {
return func(c *worker.Context) (err error) {
+ start := time.Now()
+ c.Logger().Debugf("Task '%s' started on worker '%s'", log.Magenta(c.TaskName()), log.Magenta(c.WorkerID()))
+
trx, err := db.Begin()
if err != nil {
+ err = c.Failure(err)
+ c.Logger().Debugf("Task '%s' finished in %s", log.Magenta(c.TaskName()), log.Magenta(time.Since(start).String()))
return err
}
@@ -44,24 +48,36 @@ func WorkerSetup(logger log.Logger) worker.MiddlewareFunc {
Emailer: emailer,
})
+ //In case it panics somewhere
defer func() {
if r := recover(); r != nil {
- err = fmt.Errorf("%v\n%v", r, string(debug.Stack()))
-
- if trx != nil {
- trx.Rollback()
+ err, ok := r.(error)
+ if !ok {
+ err = fmt.Errorf("%v", r)
}
+ c.Failure(err)
+ trx.Rollback()
+ c.Logger().Debugf("Task '%s' finished in %s (rolled back)", log.Magenta(c.TaskName()), log.Magenta(time.Since(start).String()))
}
}()
- start := time.Now()
- c.Logger().Debugf("Task '%s' started on worker '%s'", log.Magenta(c.TaskName()), log.Magenta(c.WorkerID()))
+ //Execute the chain
if err = next(c); err != nil {
- panic(err)
+ trx.Rollback()
+ c.Logger().Debugf("Task '%s' finished in %s (rolled back)", log.Magenta(c.TaskName()), log.Magenta(time.Since(start).String()))
+ return err
}
- trx.Commit()
- c.Logger().Debugf("Task '%s' finished in %s", log.Magenta(c.TaskName()), log.Magenta(time.Since(start).String()))
- return err
+
+ //No errors, so try to commit it
+ if err = trx.Commit(); err != nil {
+ c.Logger().Errorf("Failed to commit request with: %s", err.Error())
+ c.Logger().Debugf("Task '%s' finished in %s (rolled back)", log.Magenta(c.TaskName()), log.Magenta(time.Since(start).String()))
+ return err
+ }
+
+ //Still no errors, everything is fine!
+ c.Logger().Debugf("Task '%s' finished in %s (committed)", log.Magenta(c.TaskName()), log.Magenta(time.Since(start).String()))
+ return nil
}
}
}
@@ -80,11 +96,12 @@ func WebSetup(logger log.Logger) web.MiddlewareFunc {
trx, err := db.Begin()
if err != nil {
+ err = c.Failure(err)
+ c.Logger().Debugf("%s finished in %s", path, log.Magenta(time.Since(start).String()))
return err
}
c.SetActiveTransaction(trx)
-
c.SetServices(&app.Services{
Tenants: postgres.NewTenantStorage(trx),
OAuth: &oauth.HTTPService{},
@@ -95,25 +112,36 @@ func WebSetup(logger log.Logger) web.MiddlewareFunc {
Emailer: emailer,
})
+ //In case it panics somewhere
defer func() {
if r := recover(); r != nil {
- err := fmt.Errorf("%v\n%v", r, string(debug.Stack()))
+ err, ok := r.(error)
+ if !ok {
+ err = fmt.Errorf("%v", r)
+ }
c.Failure(err)
- c.Logger().Debugf("%s finished in %s", path, log.Magenta(time.Since(start).String()))
c.Rollback()
+ c.Logger().Debugf("%s finished in %s (rolled back)", path, log.Magenta(time.Since(start).String()))
}
}()
- if err = next(c); err != nil {
+ //Execute the chain
+ if err := next(c); err != nil {
+ c.Rollback()
+ c.Logger().Debugf("%s finished in %s (rolled back)", path, log.Magenta(time.Since(start).String()))
return err
}
- if err = c.Commit(); err != nil {
+ //No errors, so try to commit it
+ if err := c.Commit(); err != nil {
+ c.Logger().Errorf("Failed to commit request with: %s", err.Error())
+ c.Logger().Debugf("%s finished in %s (rolled back)", path, log.Magenta(time.Since(start).String()))
return err
}
- c.Logger().Debugf("%s finished in %s", path, log.Magenta(time.Since(start).String()))
- return err
+ //Still no errors, everything is fine!
+ c.Logger().Debugf("%s finished in %s (committed)", path, log.Magenta(time.Since(start).String()))
+ return nil
}
}
}
diff --git a/app/pkg/dbx/dbx.go b/app/pkg/dbx/dbx.go
index 59b4e378f..87c7e035d 100644
--- a/app/pkg/dbx/dbx.go
+++ b/app/pkg/dbx/dbx.go
@@ -11,6 +11,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
"github.com/mattes/migrate"
@@ -28,12 +29,12 @@ func New() *Database {
// NewWithLogger creates a new Database instance with logging or panic
func NewWithLogger(logger log.Logger) *Database {
conn, err := sql.Open("postgres", env.MustGet("DATABASE_URL"))
- conn.SetMaxIdleConns(20)
- conn.SetMaxOpenConns(50)
if err != nil {
- panic(err)
+ panic(errors.Wrap(err, "failed to open connection to the database"))
}
+ conn.SetMaxIdleConns(20)
+ conn.SetMaxOpenConns(50)
return &Database{conn, logger, NewRowMapper()}
}
@@ -47,7 +48,10 @@ type Database struct {
// Begin returns a new SQL transaction
func (db Database) Begin() (*Trx, error) {
tx, err := db.conn.Begin()
- return &Trx{tx: tx, logger: db.logger, mapper: db.mapper}, err
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to start new transaction")
+ }
+ return &Trx{tx: tx, logger: db.logger, mapper: db.mapper}, nil
}
// Close connection to database
@@ -61,12 +65,12 @@ func (db Database) Close() error {
func (db Database) load(path string) {
content, err := ioutil.ReadFile(env.Path(path))
if err != nil {
- panic(err)
+ panic(errors.Wrap(err, "failed to read file %s", path))
}
_, err = db.conn.Exec(string(content))
if err != nil {
- panic(err)
+ panic(errors.Wrap(err, "failed to execute %s", path))
}
}
@@ -77,7 +81,7 @@ func (db Database) Seed() {
}
}
-// Migrate the database to latest verion
+// Migrate the database to latest version
func (db Database) Migrate() {
db.logger.Infof("Running migrations...")
@@ -118,9 +122,14 @@ func (trx Trx) Execute(command string, args ...interface{}) (int64, error) {
result, err := trx.tx.Exec(command, args...)
if err != nil {
- return 0, err
+ return 0, errors.Wrap(err, "failed to execute trx.Execute")
+ }
+
+ rows, err := result.RowsAffected()
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to execute RowsAffected")
}
- return result.RowsAffected()
+ return rows, nil
}
// Scalar returns first row and first column
@@ -135,10 +144,13 @@ func (trx Trx) Scalar(data interface{}, command string, args ...interface{}) err
row := trx.tx.QueryRow(command, args...)
err := row.Scan(data)
- if err == sql.ErrNoRows {
- return app.ErrNotFound
+ if err != nil {
+ if err == sql.ErrNoRows {
+ return app.ErrNotFound
+ }
+ return errors.Wrap(err, "failed to execute trx.Scalar")
}
- return err
+ return nil
}
// Get first row and bind to given data
@@ -153,13 +165,17 @@ func (trx Trx) Get(data interface{}, command string, args ...interface{}) error
rows, err := trx.tx.Query(command, args...)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to execute trx.Get")
}
- defer rows.Close()
+ defer rows.Close()
if rows.Next() {
columns, _ := rows.Columns()
- return trx.mapper.Map(data, columns, rows.Scan)
+ err := trx.mapper.Map(data, columns, rows.Scan)
+ if err != nil {
+ return errors.Wrap(err, "failed to map result to model")
+ }
+ return nil
}
return app.ErrNotFound
@@ -175,22 +191,19 @@ func (trx Trx) QueryIntArray(command string, args ...interface{}) ([]int, error)
}()
}
- values := make([]int, 0)
- var value int
-
rows, err := trx.tx.Query(command, args...)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to execute trx.QueryIntArray")
}
- if rows != nil {
- defer rows.Close()
- for rows.Next() {
- if err := rows.Scan(&value); err != nil {
- return nil, err
- }
- values = append(values, value)
+ defer rows.Close()
+ values := make([]int, 0)
+ for rows.Next() {
+ var value int
+ if err := rows.Scan(&value); err != nil {
+ return nil, errors.Wrap(err, "failed to execute row.Scan")
}
+ values = append(values, value)
}
return values, nil
@@ -207,11 +220,12 @@ func (trx Trx) Exists(command string, args ...interface{}) (bool, error) {
}
rows, err := trx.tx.Query(command, args...)
- if rows != nil {
- defer rows.Close()
- return rows.Next(), nil
+ if err != nil {
+ return false, errors.Wrap(err, "failed to execute trx.Exists")
}
- return false, err
+
+ defer rows.Close()
+ return rows.Next(), nil
}
// Count returns number of rows
@@ -225,12 +239,16 @@ func (trx Trx) Count(command string, args ...interface{}) (int, error) {
}
rows, err := trx.tx.Query(command, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to execute trx.Count")
+ }
+
defer rows.Close()
count := 0
- for rows != nil && rows.Next() {
+ for rows.Next() {
count++
}
- return count, err
+ return count, nil
}
//Select all matched rows bind to given data
@@ -245,10 +263,10 @@ func (trx Trx) Select(data interface{}, command string, args ...interface{}) err
rows, err := trx.tx.Query(command, args...)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to execute trx.Select")
}
- defer rows.Close()
+ defer rows.Close()
sliceType := reflect.TypeOf(data).Elem()
items := reflect.New(sliceType).Elem()
itemType := sliceType.Elem().Elem()
@@ -259,7 +277,7 @@ func (trx Trx) Select(data interface{}, command string, args ...interface{}) err
}
item := reflect.New(itemType)
if err = trx.mapper.Map(item.Interface(), columns, rows.Scan); err != nil {
- return err
+ return errors.Wrap(err, "failed to map result to model")
}
items = reflect.Append(items, item)
}
@@ -270,10 +288,18 @@ func (trx Trx) Select(data interface{}, command string, args ...interface{}) err
// Commit current transaction
func (trx Trx) Commit() error {
- return trx.tx.Commit()
+ err := trx.tx.Commit()
+ if err != nil {
+ return errors.Wrap(err, "failed to commit transaction")
+ }
+ return nil
}
// Rollback current transaction
func (trx Trx) Rollback() error {
- return trx.tx.Rollback()
+ err := trx.tx.Rollback()
+ if err != nil {
+ return errors.Wrap(err, "failed to rollback transaction")
+ }
+ return nil
}
diff --git a/app/pkg/email/mailgun/mailgun.go b/app/pkg/email/mailgun/mailgun.go
index 63c458825..a09b4c25b 100644
--- a/app/pkg/email/mailgun/mailgun.go
+++ b/app/pkg/email/mailgun/mailgun.go
@@ -8,6 +8,7 @@ import (
"strings"
"github.com/getfider/fider/app/pkg/email"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
)
@@ -73,7 +74,7 @@ func (s *Sender) BatchSend(templateName string, params email.Params, from string
if isBatch {
json, err := json.Marshal(recipientVariables)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to marshal recipient variables")
}
form.Add("recipient-variables", string(json))
@@ -88,7 +89,7 @@ func (s *Sender) BatchSend(templateName string, params email.Params, from string
url := fmt.Sprintf(baseURL, s.domain)
request, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))
if err != nil {
- return err
+ return errors.Wrap(err, "failed to create POST request")
}
request.SetBasicAuth("api", s.apiKey)
@@ -96,8 +97,7 @@ func (s *Sender) BatchSend(templateName string, params email.Params, from string
resp, err := http.DefaultClient.Do(request)
if err != nil {
- s.logger.Errorf("Failed to send email")
- return err
+ return errors.Wrap(err, "failed to send email with template %s", templateName)
}
defer resp.Body.Close()
diff --git a/app/pkg/email/smtp/smtp.go b/app/pkg/email/smtp/smtp.go
index c39431287..c644fe212 100644
--- a/app/pkg/email/smtp/smtp.go
+++ b/app/pkg/email/smtp/smtp.go
@@ -5,6 +5,7 @@ import (
gosmtp "net/smtp"
"github.com/getfider/fider/app/pkg/email"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
)
@@ -49,8 +50,7 @@ func (s *Sender) Send(templateName string, params email.Params, from string, to
auth := gosmtp.PlainAuth("", s.username, s.password, s.host)
err := gosmtp.SendMail(servername, auth, email.NoReply, []string{to.Address}, []byte(body))
if err != nil {
- s.logger.Errorf("Failed to send email")
- return err
+ return errors.Wrap(err, "failed to send email with template %s", templateName)
}
s.logger.Debugf("Email sent.")
return nil
@@ -60,7 +60,7 @@ func (s *Sender) Send(templateName string, params email.Params, from string, to
func (s *Sender) BatchSend(templateName string, params email.Params, from string, to []email.Recipient) error {
for _, r := range to {
if err := s.Send(templateName, params, from, r); err != nil {
- return err
+ return errors.Wrap(err, "failed to batch send email to %d recipients", len(to))
}
}
return nil
diff --git a/app/pkg/errors/errors.go b/app/pkg/errors/errors.go
new file mode 100644
index 000000000..e35fc723f
--- /dev/null
+++ b/app/pkg/errors/errors.go
@@ -0,0 +1,78 @@
+package errors
+
+import (
+ stdError "errors"
+ "fmt"
+ "runtime"
+)
+
+type theError struct {
+ text string
+ cause error
+}
+
+func caller(skip int) (string, int) {
+ _, file, line, _ := runtime.Caller(skip)
+ file = trimBasePath(file)
+ return file, line
+}
+
+//New creates a new error
+func New(text string) error {
+ file, line := caller(2)
+ return stdError.New(fmt.Sprintf("%s (%s:%d)", text, file, line))
+}
+
+//Wrap existing error with additional text
+func Wrap(err error, format string, a ...interface{}) error {
+ return wrap(err, 0, format, a...)
+}
+
+//Stack add current code location without adding more info
+func Stack(err error) error {
+ return wrap(err, 0, "")
+}
+
+//StackN add code location of N steps before without adding more info
+func StackN(err error, skip int) error {
+ return wrap(err, skip, "")
+}
+
+func wrap(err error, skip int, format string, a ...interface{}) error {
+ if err == nil {
+ return err
+ }
+
+ file, line := caller(3 + skip)
+
+ text := ""
+ if format != "" {
+ text = fmt.Sprintf("%s (%s:%d)", fmt.Sprintf(format, a...), file, line)
+ } else {
+ text = fmt.Sprintf("%s:%d", file, line)
+ }
+
+ casted, ok := err.(*theError)
+ if ok {
+ text = fmt.Sprintf("%s\n- %s", text, casted.text)
+ }
+
+ return &theError{
+ text: text,
+ cause: Cause(err),
+ }
+}
+
+//Cause returns the original cause of the error stack
+func Cause(err error) error {
+ casted, ok := err.(*theError)
+ if ok {
+ return casted.cause
+ }
+ return err
+}
+
+//Error formats the error trace into human readable
+func (err *theError) Error() string {
+ return fmt.Sprintf("Error Trace: \n- %s\n- %v", err.text, err.cause)
+}
diff --git a/app/pkg/errors/errors_test.go b/app/pkg/errors/errors_test.go
new file mode 100644
index 000000000..87b910a2c
--- /dev/null
+++ b/app/pkg/errors/errors_test.go
@@ -0,0 +1,79 @@
+package errors_test
+
+import (
+ "testing"
+
+ "github.com/getfider/fider/app/pkg/errors"
+
+ . "github.com/onsi/gomega"
+)
+
+func TestNewError(t *testing.T) {
+ RegisterTestingT(t)
+
+ first := errors.New("document not found")
+ Expect(first.Error()).To(Equal("document not found (app/pkg/errors/errors_test.go:14)"))
+}
+
+func TestWrappedError(t *testing.T) {
+ RegisterTestingT(t)
+
+ first := errors.New("document not found")
+ wrapped := errors.Wrap(first, "could not create user '%s'", "John")
+ wrappedAgain := errors.Wrap(wrapped, "failed to register new user")
+
+ Expect(first.Error()).To(Equal(`document not found (app/pkg/errors/errors_test.go:21)`))
+ Expect(wrapped.Error()).To(Equal(`Error Trace:
+- could not create user 'John' (app/pkg/errors/errors_test.go:22)
+- document not found (app/pkg/errors/errors_test.go:21)`))
+ Expect(wrappedAgain.Error()).To(Equal(`Error Trace:
+- failed to register new user (app/pkg/errors/errors_test.go:23)
+- could not create user 'John' (app/pkg/errors/errors_test.go:22)
+- document not found (app/pkg/errors/errors_test.go:21)`))
+
+ Expect(errors.Cause(wrapped)).To(Equal(first))
+ Expect(errors.Cause(first)).To(Equal(first))
+ Expect(errors.Cause(wrappedAgain)).To(Equal(first))
+}
+
+func TestWrapAndStack(t *testing.T) {
+ RegisterTestingT(t)
+
+ first := errors.New("document not found")
+ wrapped := errors.Wrap(first, "could not create user")
+ stacked := errors.Stack(wrapped)
+ stackedTwice := errors.Stack(stacked)
+
+ Expect(stackedTwice.Error()).To(Equal(`Error Trace:
+- app/pkg/errors/errors_test.go:45
+- app/pkg/errors/errors_test.go:44
+- could not create user (app/pkg/errors/errors_test.go:43)
+- document not found (app/pkg/errors/errors_test.go:42)`))
+
+ Expect(errors.Cause(stacked)).To(Equal(first))
+ Expect(errors.Cause(stackedTwice)).To(Equal(first))
+}
+
+func doSomething(err error) error {
+ return errors.StackN(err, 1)
+}
+
+func TestStackN(t *testing.T) {
+ RegisterTestingT(t)
+
+ first := errors.New("document not found")
+ err := doSomething(first)
+ Expect(err.Error()).To(Equal(`Error Trace:
+- app/pkg/errors/errors_test.go:65
+- document not found (app/pkg/errors/errors_test.go:64)`))
+
+ Expect(errors.Cause(err)).To(Equal(first))
+}
+
+func TestNilErrors(t *testing.T) {
+ RegisterTestingT(t)
+
+ Expect(errors.Cause(nil)).To(BeNil())
+ Expect(errors.Stack(nil)).To(BeNil())
+ Expect(errors.Wrap(nil, "", "")).To(BeNil())
+}
diff --git a/app/pkg/errors/path.go b/app/pkg/errors/path.go
new file mode 100644
index 000000000..fa43a5045
--- /dev/null
+++ b/app/pkg/errors/path.go
@@ -0,0 +1,31 @@
+package errors
+
+import (
+ "runtime"
+ "strings"
+)
+
+var (
+ prefixSize int
+ basePath string
+)
+
+func init() {
+ _, file, _, ok := runtime.Caller(0)
+ if file == "?" {
+ return
+ }
+ if ok {
+ size := len(file)
+ suffix := len("app/pkg/errors/path.go")
+ basePath = file[:size-suffix]
+ prefixSize = len(basePath)
+ }
+}
+
+func trimBasePath(filename string) string {
+ if strings.HasPrefix(filename, basePath) {
+ return filename[prefixSize:]
+ }
+ return filename
+}
diff --git a/app/pkg/jwt/jwt.go b/app/pkg/jwt/jwt.go
index 94b92908c..f3d7c57e5 100644
--- a/app/pkg/jwt/jwt.go
+++ b/app/pkg/jwt/jwt.go
@@ -4,6 +4,7 @@ import (
jwtgo "github.com/dgrijalva/jwt-go"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
)
var jwtSecret = env.MustGet("JWT_SECRET")
@@ -11,27 +12,31 @@ var jwtSecret = env.MustGet("JWT_SECRET")
//Encode creates new JWT tokens with given claims
func Encode(claims jwtgo.Claims) (string, error) {
jwtToken := jwtgo.NewWithClaims(jwtgo.GetSigningMethod("HS256"), claims)
- return jwtToken.SignedString([]byte(jwtSecret))
+ token, err := jwtToken.SignedString([]byte(jwtSecret))
+ if err != nil {
+ return "", errors.Wrap(err, "failed to encode the requested claims")
+ }
+ return token, nil
}
//DecodeFiderClaims extract claims from JWT tokens
func DecodeFiderClaims(token string) (*models.FiderClaims, error) {
claims := &models.FiderClaims{}
err := decode(token, claims)
- if err == nil {
- return claims, nil
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to decode Fider claims")
}
- return nil, err
+ return claims, nil
}
//DecodeOAuthClaims extract OAuthClaims from given JWT token
func DecodeOAuthClaims(token string) (*models.OAuthClaims, error) {
claims := &models.OAuthClaims{}
err := decode(token, claims)
- if err == nil {
- return claims, nil
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to decode OAuth claims")
}
- return nil, err
+ return claims, nil
}
func decode(token string, claims jwtgo.Claims) error {
diff --git a/app/pkg/oauth/http.go b/app/pkg/oauth/http.go
index c512f59c1..f0b2bbd99 100644
--- a/app/pkg/oauth/http.go
+++ b/app/pkg/oauth/http.go
@@ -2,13 +2,13 @@ package oauth
import (
"encoding/json"
- "fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
+ "github.com/getfider/fider/app/pkg/errors"
"golang.org/x/oauth2"
"golang.org/x/oauth2/facebook"
"golang.org/x/oauth2/github"
@@ -82,10 +82,15 @@ func doGet(url string, v interface{}) error {
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to request GET %s", url)
+ }
+
+ err = json.Unmarshal(bytes, v)
+ if err != nil {
+ return errors.Wrap(err, "failed unmarshal response")
}
- return json.Unmarshal(bytes, v)
+ return nil
}
//HTTPService implements real OAuth operations using Golang's oauth2 package
@@ -111,12 +116,12 @@ func (p *HTTPService) GetProfile(authEndpoint string, provider string, code stri
settings := oauthSettings[provider]
oauthToken, err := settings.config(authEndpoint).Exchange(oauth2.NoContext, code)
if err != nil {
- return nil, fmt.Errorf("OAuth code Exchange for %s failed with %s", provider, err)
+ return nil, errors.Wrap(err, "failed to exchange OAuth2 code with %s", provider)
}
profile := &UserProfile{}
if err = doGet(settings.profileURL(oauthToken), profile); err != nil {
- return nil, fmt.Errorf("HTTP Get profile for %s failed with %s", provider, err)
+ return nil, err
}
//GitHub allows users to omit name, so we use their login name
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 2ed9d429d..5ba0a3d39 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -16,6 +16,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/validate"
@@ -140,7 +141,7 @@ func (ctx *Context) SetTenant(tenant *models.Tenant) {
func (ctx *Context) BindTo(i actions.Actionable) *validate.Result {
err := ctx.engine.binder.Bind(i.Initialize(), ctx)
if err != nil {
- return validate.Error(err)
+ return validate.Error(errors.Wrap(err, "failed to bind request to action"))
}
if !i.IsAuthorized(ctx.User(), ctx.Services()) {
return validate.Unauthorized()
@@ -178,11 +179,11 @@ func (ctx *Context) NotFound() error {
//Failure returns a 500 page
func (ctx *Context) Failure(err error) error {
- if err == app.ErrNotFound {
+ err = errors.StackN(err, 1)
+ if errors.Cause(err) == app.ErrNotFound {
return ctx.NotFound()
}
- url := ctx.BaseURL() + ctx.Request.RequestURI
tenant := "undefined"
if ctx.Tenant() != nil {
tenant = fmt.Sprintf("%s (%d)", ctx.Tenant().Name, ctx.Tenant().ID)
@@ -193,6 +194,7 @@ func (ctx *Context) Failure(err error) error {
user = fmt.Sprintf("%s (%d)", ctx.User().Name, ctx.User().ID)
}
+ url := ctx.BaseURL() + ctx.Request.RequestURI
message := fmt.Sprintf("URL: %s\nTenant: %s\nUser: %s\n%s", url, tenant, user, err.Error())
ctx.Logger().Errorf(log.Red(message))
ctx.Render(http.StatusInternalServerError, "500.html", Map{})
@@ -278,7 +280,7 @@ func (ctx *Context) AddAuthCookie(user *models.User) (string, error) {
})
if err != nil {
- return token, err
+ return token, errors.Wrap(err, "failed to add auth cookie")
}
ctx.AddCookie(CookieAuthName, token, time.Now().Add(365*24*time.Hour))
@@ -385,11 +387,12 @@ func (ctx *Context) Param(name string) string {
//ParamAsInt returns parameter as int
func (ctx *Context) ParamAsInt(name string) (int, error) {
- val, err := strconv.Atoi(ctx.Param(name))
+ value := ctx.Param(name)
+ intValue, err := strconv.Atoi(value)
if err != nil {
- return 0, err
+ return 0, errors.Wrap(err, "failed to parse %s to integer", value)
}
- return int(val), nil
+ return intValue, nil
}
//RenderVars returns all registered RenderVar
@@ -435,7 +438,7 @@ func (ctx *Context) String(code int, text string) error {
func (ctx *Context) JSON(code int, i interface{}) error {
b, err := json.Marshal(i)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to marshal response to JSON")
}
return ctx.Blob(code, JSONContentType, b)
}
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index 36b1651e1..c461e8b8a 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -12,6 +12,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/worker"
"github.com/julienschmidt/httprouter"
@@ -84,7 +85,7 @@ func (e *Engine) Start(address string) {
if autoSSL == "true" {
certManager, err = NewCertificateManager(certFile, keyFile, "certs")
if err != nil {
- panic(err)
+ panic(errors.Wrap(err, "failed to initialize CertificateManager"))
}
server.TLSConfig = &tls.Config{
@@ -103,7 +104,7 @@ func (e *Engine) Start(address string) {
}
if err != nil {
- panic(err)
+ panic(errors.Wrap(err, "failed to start server"))
}
}
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index ef4620fda..34677dd33 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -9,6 +9,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/oauth"
)
@@ -47,7 +48,7 @@ func (r *Renderer) add(name string) *template.Template {
file := env.Path("/views", name)
tpl, err := template.ParseFiles(base, file)
if err != nil {
- panic(err)
+ panic(errors.Wrap(err, "failed to parse template %s", file))
}
r.templates[name] = tpl
@@ -115,5 +116,9 @@ func (r *Renderer) Render(w io.Writer, name string, data interface{}, ctx *Conte
}
}
- return tmpl.Execute(w, m)
+ err := tmpl.Execute(w, m)
+ if err != nil {
+ return errors.Wrap(err, "failed to execute template %s", name)
+ }
+ return nil
}
diff --git a/app/pkg/web/ssl.go b/app/pkg/web/ssl.go
index fd81b7787..f579eef7e 100644
--- a/app/pkg/web/ssl.go
+++ b/app/pkg/web/ssl.go
@@ -5,6 +5,7 @@ import (
"crypto/x509"
"net/http"
+ "github.com/getfider/fider/app/pkg/errors"
"golang.org/x/crypto/acme/autocert"
)
@@ -28,12 +29,12 @@ func NewCertificateManager(certFile, keyFile, cacheDir string) (*CertificateMana
var err error
manager.cert, err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to load X509KeyPair for %s and %s", certFile, keyFile)
}
manager.leaf, err = x509.ParseCertificate(manager.cert.Certificate[0])
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to parse x509 certificate")
}
}
diff --git a/app/pkg/worker/context.go b/app/pkg/worker/context.go
index 846b2245b..38ff9e6eb 100644
--- a/app/pkg/worker/context.go
+++ b/app/pkg/worker/context.go
@@ -1,8 +1,11 @@
package worker
import (
+ "fmt"
+
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
)
@@ -82,3 +85,22 @@ func (c *Context) Services() *app.Services {
func (c *Context) Logger() log.Logger {
return c.logger
}
+
+//Failure logs details of error
+func (c *Context) Failure(err error) error {
+ err = errors.StackN(err, 1)
+
+ tenant := "undefined"
+ if c.Tenant() != nil {
+ tenant = fmt.Sprintf("%s (%d)", c.Tenant().Name, c.Tenant().ID)
+ }
+
+ user := "not signed in"
+ if c.User() != nil {
+ user = fmt.Sprintf("%s (%d)", c.User().Name, c.User().ID)
+ }
+
+ message := fmt.Sprintf("Task: %s\nTenant: %s\nUser: %s\n%s", c.taskName, tenant, user, err.Error())
+ c.logger.Errorf(log.Red(message))
+ return err
+}
diff --git a/app/pkg/worker/worker.go b/app/pkg/worker/worker.go
index 892074fb6..b89af2782 100644
--- a/app/pkg/worker/worker.go
+++ b/app/pkg/worker/worker.go
@@ -1,8 +1,6 @@
package worker
import (
- "fmt"
-
"github.com/getfider/fider/app/pkg/log"
)
@@ -58,10 +56,7 @@ func (w *BackgroundWorker) Run(id string) {
logger: w.logger,
}
- if err := w.middleware(task.Job)(c); err != nil {
- w.logError(task, c, err)
- }
-
+ w.middleware(task.Job)(c)
}
}
@@ -84,18 +79,3 @@ func (w *BackgroundWorker) Length() int {
func (w *BackgroundWorker) Use(middleware MiddlewareFunc) {
w.middleware = middleware
}
-
-func (w *BackgroundWorker) logError(task Task, ctx *Context, err error) {
- tenant := "undefined"
- if ctx.Tenant() != nil {
- tenant = fmt.Sprintf("%s (%d)", ctx.Tenant().Name, ctx.Tenant().ID)
- }
-
- user := "not signed in"
- if ctx.User() != nil {
- user = fmt.Sprintf("%s (%d)", ctx.User().Name, ctx.User().ID)
- }
-
- message := fmt.Sprintf("Task: %s\nTenant: %s\nUser: %s\n%s", task.Name, tenant, user, err.Error())
- w.logger.Errorf(log.Red(message))
-}
diff --git a/app/storage/inmemory/user.go b/app/storage/inmemory/user.go
index 9ac25bfa2..8ab4c01c0 100644
--- a/app/storage/inmemory/user.go
+++ b/app/storage/inmemory/user.go
@@ -1,10 +1,9 @@
package inmemory
import (
- "errors"
-
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
)
// UserStorage is used for user operations
@@ -65,7 +64,7 @@ func (s *UserStorage) Register(user *models.User) error {
user.ID = s.lastID
}
_, err := s.GetByEmail(user.Email)
- if err == app.ErrNotFound || user.Email == "" {
+ if errors.Cause(err) == app.ErrNotFound || user.Email == "" {
s.users = append(s.users, user)
return nil
}
diff --git a/app/storage/postgres/idea.go b/app/storage/postgres/idea.go
index bf8510e51..64114fc49 100644
--- a/app/storage/postgres/idea.go
+++ b/app/storage/postgres/idea.go
@@ -1,7 +1,6 @@
package postgres
import (
- "errors"
"fmt"
"strconv"
"time"
@@ -10,6 +9,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/gosimple/slug"
"github.com/lib/pq"
)
@@ -221,22 +221,38 @@ func (s *IdeaStorage) getSingle(query string, args ...interface{}) (*models.Idea
// GetByID returns idea by given id
func (s *IdeaStorage) GetByID(ideaID int) (*models.Idea, error) {
- return s.getSingle(s.getIdeaQuery("i.tenant_id = $1 AND i.id = $2"), s.tenant.ID, ideaID)
+ idea, err := s.getSingle(s.getIdeaQuery("i.tenant_id = $1 AND i.id = $2"), s.tenant.ID, ideaID)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get idea with id '%d'", ideaID)
+ }
+ return idea, nil
}
// GetBySlug returns idea by tenant and slug
func (s *IdeaStorage) GetBySlug(slug string) (*models.Idea, error) {
- return s.getSingle(s.getIdeaQuery("i.tenant_id = $1 AND i.slug = $2"), s.tenant.ID, slug)
+ idea, err := s.getSingle(s.getIdeaQuery("i.tenant_id = $1 AND i.slug = $2"), s.tenant.ID, slug)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get idea with slug '%s'", slug)
+ }
+ return idea, nil
}
// GetByNumber returns idea by tenant and number
func (s *IdeaStorage) GetByNumber(number int) (*models.Idea, error) {
- return s.getSingle(s.getIdeaQuery("i.tenant_id = $1 AND i.number = $2"), s.tenant.ID, number)
+ idea, err := s.getSingle(s.getIdeaQuery("i.tenant_id = $1 AND i.number = $2"), s.tenant.ID, number)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get idea with number '%d'", number)
+ }
+ return idea, nil
}
// GetAll returns all tenant ideas
func (s *IdeaStorage) GetAll() ([]*models.Idea, error) {
- return s.Search("", "all", []string{})
+ ideas, err := s.Search("", "all", []string{})
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get all ideas")
+ }
+ return ideas, nil
}
// CountPerStatus returns total number of ideas per status
@@ -244,7 +260,7 @@ func (s *IdeaStorage) CountPerStatus() (map[int]int, error) {
stats := []*dbStatusCount{}
err := s.trx.Select(&stats, "SELECT status, COUNT(*) AS count FROM ideas WHERE tenant_id = $1 GROUP BY status", s.tenant.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to count ideas per status")
}
result := make(map[int]int, len(stats))
for _, v := range stats {
@@ -286,7 +302,7 @@ func (s *IdeaStorage) Search(query, filter string, tags []string) ([]*models.Ide
}
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to search ideas")
}
var result = make([]*models.Idea, len(ideas))
@@ -326,7 +342,7 @@ func (s *IdeaStorage) GetCommentsByIdea(idea *models.Idea) ([]*models.Comment, e
AND i.tenant_id = $2
ORDER BY c.created_on ASC`, idea.ID, s.tenant.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed get comments of idea with id '%d'", idea.ID)
}
var result = make([]*models.Comment, len(comments))
@@ -341,7 +357,7 @@ func (s *IdeaStorage) Update(idea *models.Idea, title, description string) (*mod
_, err := s.trx.Execute(`UPDATE ideas SET title = $1, slug = $2, description = $3
WHERE id = $4 AND tenant_id = $5`, title, slug.Make(title), description, idea.ID, s.tenant.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed update idea")
}
idea.Slug = slug.Make(title)
@@ -359,7 +375,7 @@ func (s *IdeaStorage) Add(title, description string) (*models.Idea, error) {
VALUES ($1, $2, (SELECT COALESCE(MAX(number), 0) + 1 FROM ideas i WHERE i.tenant_id = $4), $3, $4, $5, $6, 0, 0)
RETURNING id`, title, slug.Make(title), description, s.tenant.ID, s.user.ID, time.Now())
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed add new idea")
}
idea, err := s.GetByID(id)
@@ -380,7 +396,7 @@ func (s *IdeaStorage) AddComment(idea *models.Idea, content string) (int, error)
if err := s.trx.Get(&id,
"INSERT INTO comments (tenant_id, idea_id, content, user_id, created_on) VALUES ($1, $2, $3, $4, $5) RETURNING id",
s.tenant.ID, idea.ID, content, s.user.ID, time.Now()); err != nil {
- return 0, err
+ return 0, errors.Wrap(err, "failed add new comment")
}
if err := s.internalAddSubscriber(idea, s.user, false); err != nil {
@@ -428,7 +444,10 @@ func (s *IdeaStorage) UpdateComment(id int, content string) error {
_, err := s.trx.Execute(`
UPDATE comments SET content = $1, edited_on = $2, edited_by_id = $3
WHERE id = $4 AND tenant_id = $5`, content, time.Now(), s.user.ID, id, s.tenant.ID)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed update comment")
+ }
+ return nil
}
// AddSupporter adds user to idea list of supporters
@@ -442,13 +461,13 @@ func (s *IdeaStorage) AddSupporter(idea *models.Idea, user *models.User) error {
s.tenant.ID, user.ID, idea.ID, time.Now())
if err != nil {
- return err
+ return errors.Wrap(err, "failed add supporter to idea")
}
if rows == 1 {
_, err := s.trx.Execute(`UPDATE ideas SET supporters = supporters + 1 WHERE id = $1 AND tenant_id = $2`, idea.ID, s.tenant.ID)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to increment idea's supporters count")
}
}
@@ -462,11 +481,14 @@ func (s *IdeaStorage) RemoveSupporter(idea *models.Idea, user *models.User) erro
}
rows, err := s.trx.Execute(`DELETE FROM idea_supporters WHERE user_id = $1 AND idea_id = $2 AND tenant_id = $3`, user.ID, idea.ID, s.tenant.ID)
+ if err != nil {
+ return errors.Wrap(err, "failed to delete idea supporter")
+ }
if rows == 1 {
_, err := s.trx.Execute(`UPDATE ideas SET supporters = supporters - 1 WHERE id = $1 AND tenant_id = $2`, idea.ID, s.tenant.ID)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to decrement idea's supporters count")
}
}
return err
@@ -488,7 +510,10 @@ func (s *IdeaStorage) internalAddSubscriber(idea *models.Idea, user *models.User
VALUES ($1, $2, $3, $4, $4, $5) ON CONFLICT %s`, conflict),
s.tenant.ID, user.ID, idea.ID, time.Now(), models.SubscriberActive,
)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed insert idea subscriber")
+ }
+ return nil
}
// RemoveSubscriber removes user from idea list of subscribers
@@ -499,7 +524,10 @@ func (s *IdeaStorage) RemoveSubscriber(idea *models.Idea, user *models.User) err
DO UPDATE SET status = 0, updated_on = $4`,
s.tenant.ID, user.ID, idea.ID, time.Now(),
)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed remove idea subscriber")
+ }
+ return nil
}
// GetActiveSubscribers based on input and settings
@@ -558,7 +586,7 @@ func (s *IdeaStorage) GetActiveSubscribers(number int, channel models.Notificati
}
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get idea number '%d' subscribers", number)
}
var result = make([]*models.User, len(users))
@@ -585,7 +613,7 @@ func (s *IdeaStorage) SetResponse(idea *models.Idea, text string, status int) er
WHERE id = $1 and tenant_id = $2
`, idea.ID, s.tenant.ID, text, respondedOn, s.user.ID, status)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to update idea's response")
}
idea.Status = status
@@ -607,7 +635,7 @@ func (s *IdeaStorage) MarkAsDuplicate(idea *models.Idea, original *models.Idea)
var users []*dbUser
err := s.trx.Select(&users, "SELECT user_id AS id FROM idea_supporters WHERE idea_id = $1 AND tenant_id = $2", idea.ID, s.tenant.ID)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to get supporters of idea with id '%d'", idea.ID)
}
for _, u := range users {
@@ -622,7 +650,7 @@ func (s *IdeaStorage) MarkAsDuplicate(idea *models.Idea, original *models.Idea)
WHERE id = $1 and tenant_id = $2
`, idea.ID, s.tenant.ID, original.ID, respondedOn, s.user.ID, models.IdeaDuplicate)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to update idea's response")
}
idea.Status = models.IdeaDuplicate
@@ -641,16 +669,24 @@ func (s *IdeaStorage) MarkAsDuplicate(idea *models.Idea, original *models.Idea)
// IsReferenced returns true if another idea is referencing given idea
func (s *IdeaStorage) IsReferenced(idea *models.Idea) (bool, error) {
- return s.trx.Exists(`
+ exists, err := s.trx.Exists(`
SELECT 1 FROM ideas i
INNER JOIN ideas o
ON o.tenant_id = i.tenant_id
AND o.id = i.original_id
WHERE i.tenant_id = $1
AND o.id = $2`, s.tenant.ID, idea.ID)
+ if err != nil {
+ return false, errors.Wrap(err, "failed to check if idea is referenced")
+ }
+ return exists, nil
}
// SupportedBy returns a list of Idea ID supported by given user
func (s *IdeaStorage) SupportedBy() ([]int, error) {
- return s.trx.QueryIntArray("SELECT idea_id FROM idea_supporters WHERE user_id = $1 AND tenant_id = $2", s.user.ID, s.tenant.ID)
+ ideas, err := s.trx.QueryIntArray("SELECT idea_id FROM idea_supporters WHERE user_id = $1 AND tenant_id = $2", s.user.ID, s.tenant.ID)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get user's supported ideas")
+ }
+ return ideas, nil
}
diff --git a/app/storage/postgres/idea_test.go b/app/storage/postgres/idea_test.go
index 238111c2f..d8859dc3f 100644
--- a/app/storage/postgres/idea_test.go
+++ b/app/storage/postgres/idea_test.go
@@ -6,6 +6,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
. "github.com/onsi/gomega"
)
@@ -90,7 +91,7 @@ func TestIdeaStorage_GetInvalid(t *testing.T) {
ideas.SetCurrentTenant(demoTenant)
dbIdea, err := ideas.GetByID(1)
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(dbIdea).To(BeNil())
}
@@ -388,11 +389,11 @@ func TestIdeaStorage_SetResponse_AsDeleted(t *testing.T) {
ideas.SetResponse(idea, "Spam!", models.IdeaDeleted)
idea1, err := ideas.GetByNumber(idea.Number)
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(idea1).To(BeNil())
idea2, err := ideas.GetByID(idea.ID)
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(idea2).To(BeNil())
}
diff --git a/app/storage/postgres/notifications.go b/app/storage/postgres/notifications.go
index 4c295b0ed..5fccf317a 100644
--- a/app/storage/postgres/notifications.go
+++ b/app/storage/postgres/notifications.go
@@ -5,6 +5,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
)
// NotificationStorage contains read and write operations for notifications
@@ -50,7 +51,7 @@ func (s *NotificationStorage) Insert(user *models.User, title, link string, idea
RETURNING id
`, s.tenant.ID, user.ID, title, link, false, ideaID, s.user.ID, now)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to insert notification")
}
return notification, nil
}
@@ -61,7 +62,7 @@ func (s *NotificationStorage) TotalUnread() (int, error) {
if s.user != nil {
err := s.trx.Scalar(&total, "SELECT COUNT(*) FROM notifications WHERE tenant_id = $1 AND user_id = $2 AND read = false", s.tenant.ID, s.user.ID)
if err != nil {
- return 0, err
+ return 0, errors.Wrap(err, "failed count total unread notifications")
}
}
return total, nil
@@ -76,7 +77,10 @@ func (s *NotificationStorage) MarkAsRead(id int) error {
UPDATE notifications SET read = true, updated_on = $1
WHERE id = $2 AND tenant_id = $3 AND user_id = $4 AND read = false
`, time.Now(), id, s.tenant.ID, s.user.ID)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to mark notification as read")
+ }
+ return nil
}
// MarkAllAsRead of current user
@@ -88,7 +92,10 @@ func (s *NotificationStorage) MarkAllAsRead() error {
UPDATE notifications SET read = true, updated_on = $1
WHERE tenant_id = $2 AND user_id = $3 AND read = false
`, time.Now(), s.tenant.ID, s.user.ID)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to mark all notifications as read")
+ }
+ return nil
}
// GetActiveNotifications returns all unread notifications and last 30 days of read notifications
@@ -101,7 +108,7 @@ func (s *NotificationStorage) GetActiveNotifications() ([]*models.Notification,
AND (read = false OR updated_on > CURRENT_DATE - INTERVAL '30 days')
`, s.tenant.ID, s.user.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get active notifications")
}
return notifications, nil
}
@@ -115,7 +122,7 @@ func (s *NotificationStorage) GetNotification(id int) (*models.Notification, err
WHERE id = $1 AND tenant_id = $2 AND user_id = $3
`, id, s.tenant.ID, s.user.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get notifications with id '%d'", id)
}
return notification, nil
}
diff --git a/app/storage/postgres/notifications_test.go b/app/storage/postgres/notifications_test.go
index eec6f1e0a..c84b98552 100644
--- a/app/storage/postgres/notifications_test.go
+++ b/app/storage/postgres/notifications_test.go
@@ -5,6 +5,7 @@ import (
"time"
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/pkg/errors"
. "github.com/onsi/gomega"
)
@@ -139,6 +140,6 @@ func TestNotificationStorage_GetNotificationById_OtherUser(t *testing.T) {
Expect(err).To(BeNil())
not1, err = notifications.GetNotification(not1.ID)
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(not1).To(BeNil())
}
diff --git a/app/storage/postgres/tag.go b/app/storage/postgres/tag.go
index ecc4453e7..639a707d2 100644
--- a/app/storage/postgres/tag.go
+++ b/app/storage/postgres/tag.go
@@ -6,6 +6,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/gosimple/slug"
)
@@ -61,7 +62,7 @@ func (s *TagStorage) Add(name, color string, isPublic bool) (*models.Tag, error)
VALUES ($1, $2, $3, $4, $5, $6) RETURNING id
`, name, tagSlug, color, isPublic, time.Now(), s.tenant.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to add new tag")
}
return s.GetBySlug(tagSlug)
@@ -73,7 +74,7 @@ func (s *TagStorage) GetBySlug(slug string) (*models.Tag, error) {
err := s.trx.Get(&tag, "SELECT id, name, slug, color, is_public FROM tags WHERE tenant_id = $1 AND slug = $2", s.tenant.ID, slug)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get tag with slug '%s'", slug)
}
return tag.toModel(), nil
@@ -86,7 +87,7 @@ func (s *TagStorage) Update(tag *models.Tag, name, color string, isPublic bool)
_, err := s.trx.Execute(`UPDATE tags SET name = $1, slug = $2, color = $3, is_public = $4
WHERE id = $5 AND tenant_id = $6`, name, tagSlug, color, isPublic, tag.ID, s.tenant.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to update tag")
}
return s.GetBySlug(tagSlug)
@@ -96,17 +97,21 @@ func (s *TagStorage) Update(tag *models.Tag, name, color string, isPublic bool)
func (s *TagStorage) Delete(tag *models.Tag) error {
_, err := s.trx.Execute(`DELETE FROM idea_tags WHERE tag_id = $1 AND tenant_id = $2`, tag.ID, s.tenant.ID)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to remove tag with id '%d' from all ideas", tag.ID)
}
+
_, err = s.trx.Execute(`DELETE FROM tags WHERE id = $1 AND tenant_id = $2`, tag.ID, s.tenant.ID)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to delete tag with id '%d'", tag.ID)
+ }
+ return nil
}
// AssignTag adds a tag to an idea
func (s *TagStorage) AssignTag(tag *models.Tag, idea *models.Idea) error {
alreadyAssigned, err := s.trx.Exists("SELECT 1 FROM idea_tags WHERE idea_id = $1 AND tag_id = $2 AND tenant_id = $3", idea.ID, tag.ID, s.tenant.ID)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to check if tag is already assigned")
}
if alreadyAssigned {
@@ -117,7 +122,11 @@ func (s *TagStorage) AssignTag(tag *models.Tag, idea *models.Idea) error {
`INSERT INTO idea_tags (tag_id, idea_id, created_on, created_by_id, tenant_id) VALUES ($1, $2, $3, $4, $5)`,
tag.ID, idea.ID, time.Now(), s.user.ID, s.tenant.ID,
)
- return err
+
+ if err != nil {
+ return errors.Wrap(err, "failed to assign tag to idea")
+ }
+ return nil
}
// UnassignTag removes a tag from an idea
@@ -126,12 +135,16 @@ func (s *TagStorage) UnassignTag(tag *models.Tag, idea *models.Idea) error {
`DELETE FROM idea_tags WHERE tag_id = $1 AND idea_id = $2 AND tenant_id = $3`,
tag.ID, idea.ID, s.tenant.ID,
)
- return err
+
+ if err != nil {
+ return errors.Wrap(err, "failed to unassign tag from idea")
+ }
+ return nil
}
// GetAssigned returns all tags assigned to given idea
func (s *TagStorage) GetAssigned(idea *models.Idea) ([]*models.Tag, error) {
- return s.getTags(`
+ tags, err := s.getTags(`
SELECT t.id, t.name, t.slug, t.color, t.is_public
FROM tags t
INNER JOIN idea_tags it
@@ -139,6 +152,11 @@ func (s *TagStorage) GetAssigned(idea *models.Idea) ([]*models.Tag, error) {
AND it.tenant_id = t.tenant_id
WHERE it.idea_id = $1 AND t.tenant_id = $2
`, idea.ID, s.tenant.ID)
+
+ if err != nil {
+ return nil, errors.Wrap(err, "failed get assigned tags")
+ }
+ return tags, nil
}
// GetAll returns all tags
@@ -153,7 +171,11 @@ func (s *TagStorage) GetAll() ([]*models.Tag, error) {
FROM tags t
WHERE t.tenant_id = $1 %s
`, condition)
- return s.getTags(query, s.tenant.ID)
+ tags, err := s.getTags(query, s.tenant.ID)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed get all tags")
+ }
+ return tags, nil
}
// GetAll returns all tags
diff --git a/app/storage/postgres/tag_test.go b/app/storage/postgres/tag_test.go
index 3d92cdc0f..4052132d2 100644
--- a/app/storage/postgres/tag_test.go
+++ b/app/storage/postgres/tag_test.go
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/pkg/errors"
. "github.com/onsi/gomega"
)
@@ -56,7 +57,7 @@ func TestTagStorage_AddDeleteAndGet(t *testing.T) {
dbTag, err := tags.GetBySlug("bug")
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(dbTag).To(BeNil())
}
diff --git a/app/storage/postgres/tenant.go b/app/storage/postgres/tenant.go
index 93d960f2d..bd1227679 100644
--- a/app/storage/postgres/tenant.go
+++ b/app/storage/postgres/tenant.go
@@ -7,6 +7,7 @@ import (
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/dbx"
"github.com/getfider/fider/app/pkg/env"
+ "github.com/getfider/fider/app/pkg/errors"
)
type dbTenant struct {
@@ -111,7 +112,7 @@ func (s *TenantStorage) First() (*models.Tenant, error) {
err := s.trx.Get(&tenant, "SELECT id, name, subdomain, cname, invitation, welcome_message, status FROM tenants ORDER BY id LIMIT 1")
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get first tenant")
}
return tenant.toModel(), nil
@@ -123,7 +124,7 @@ func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {
err := s.trx.Get(&tenant, "SELECT id, name, subdomain, cname, invitation, welcome_message, status FROM tenants WHERE subdomain = $1 OR cname = $2 ORDER BY cname DESC", extractSubdomain(domain), domain)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get tenant with domain '%s'", domain)
}
return tenant.toModel(), nil
@@ -133,26 +134,38 @@ func (s *TenantStorage) GetByDomain(domain string) (*models.Tenant, error) {
func (s *TenantStorage) UpdateSettings(settings *models.UpdateTenantSettings) error {
query := "UPDATE tenants SET name = $1, invitation = $2, welcome_message = $3, cname = $4 WHERE id = $5"
_, err := s.trx.Execute(query, settings.Title, settings.Invitation, settings.WelcomeMessage, settings.CNAME, s.current.ID)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed update tenant settings")
+ }
+ return nil
}
// IsSubdomainAvailable returns true if subdomain is available to use
func (s *TenantStorage) IsSubdomainAvailable(subdomain string) (bool, error) {
exists, err := s.trx.Exists("SELECT id FROM tenants WHERE subdomain = $1", subdomain)
- return !exists, err
+ if err != nil {
+ return false, errors.Wrap(err, "failed to check if tenant exists with subdomain '%s'", subdomain)
+ }
+ return !exists, nil
}
// IsCNAMEAvailable returns true if cname is available to use
func (s *TenantStorage) IsCNAMEAvailable(cname string) (bool, error) {
exists, err := s.trx.Exists("SELECT id FROM tenants WHERE cname = $1 AND id <> $2", cname, s.current.ID)
- return !exists, err
+ if err != nil {
+ return false, errors.Wrap(err, "failed to check if tenant exists with CNAME '%s'", cname)
+ }
+ return !exists, nil
}
// Activate given tenant
func (s *TenantStorage) Activate(id int) error {
query := "UPDATE tenants SET status = $1 WHERE id = $2"
_, err := s.trx.Execute(query, models.TenantActive, id)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to activate tenant with id '%d'", id)
+ }
+ return nil
}
// SaveVerificationKey used by email verification process
@@ -161,9 +174,13 @@ func (s *TenantStorage) SaveVerificationKey(key string, duration time.Duration,
if request.GetUser() != nil {
userID = request.GetUser().ID
}
+
query := "INSERT INTO email_verifications (tenant_id, email, created_on, expires_on, key, name, kind, user_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"
_, err := s.trx.Execute(query, s.current.ID, request.GetEmail(), time.Now(), time.Now().Add(duration), key, request.GetName(), request.GetKind(), userID)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to save verification key for kind '%d'", request.GetKind())
+ }
+ return nil
}
// FindVerificationByKey based on current tenant
@@ -173,7 +190,7 @@ func (s *TenantStorage) FindVerificationByKey(kind models.EmailVerificationKind,
query := "SELECT id, email, name, key, created_on, verified_on, expires_on, kind, user_id FROM email_verifications WHERE key = $1 AND kind = $2 LIMIT 1"
err := s.trx.Get(&verification, query, key, kind)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get email verification by its key")
}
return verification.toModel(), nil
@@ -183,7 +200,10 @@ func (s *TenantStorage) FindVerificationByKey(kind models.EmailVerificationKind,
func (s *TenantStorage) SetKeyAsVerified(key string) error {
query := "UPDATE email_verifications SET verified_on = $1 WHERE tenant_id = $2 AND key = $3"
_, err := s.trx.Execute(query, time.Now(), s.current.ID, key)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to update verified date of email verification request")
+ }
+ return nil
}
func extractSubdomain(hostname string) string {
diff --git a/app/storage/postgres/tenant_test.go b/app/storage/postgres/tenant_test.go
index 3c0e220b1..68d4ee808 100644
--- a/app/storage/postgres/tenant_test.go
+++ b/app/storage/postgres/tenant_test.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app"
. "github.com/onsi/gomega"
@@ -63,7 +64,7 @@ func TestTenantStorage_Empty_First(t *testing.T) {
trx.Execute("TRUNCATE tenants CASCADE")
tenant, err := tenants.First()
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(tenant).To(BeNil())
}
@@ -180,7 +181,7 @@ func TestTenantStorage_SaveFindSet_VerificationKey(t *testing.T) {
//Wrong kind should not find it
result, err = tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, "s3cr3tk3y")
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(result).To(BeNil())
}
@@ -221,6 +222,6 @@ func TestTenantStorage_FindUnknownVerificationKey(t *testing.T) {
//Find and check values
result, err := tenants.FindVerificationByKey(models.EmailVerificationKindSignIn, "blahblahblah")
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(result).To(BeNil())
}
diff --git a/app/storage/postgres/user.go b/app/storage/postgres/user.go
index 292b20261..9a3ae93b5 100644
--- a/app/storage/postgres/user.go
+++ b/app/storage/postgres/user.go
@@ -9,6 +9,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/dbx"
+ "github.com/getfider/fider/app/pkg/errors"
)
type dbUser struct {
@@ -78,12 +79,20 @@ func (s *UserStorage) SetCurrentUser(user *models.User) {
// GetByID returns a user based on given id
func (s *UserStorage) GetByID(userID int) (*models.User, error) {
- return getUser(s.trx, "id = $1", userID)
+ user, err := getUser(s.trx, "id = $1", userID)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get user with id '%d'", userID)
+ }
+ return user, nil
}
// GetByEmail returns a user based on given email
func (s *UserStorage) GetByEmail(email string) (*models.User, error) {
- return getUser(s.trx, "email = $1 AND tenant_id = $2", email, s.tenant.ID)
+ user, err := getUser(s.trx, "email = $1 AND tenant_id = $2", email, s.tenant.ID)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to get user with email '%s'", email)
+ }
+ return user, nil
}
// GetByProvider returns a user based on provider details
@@ -99,7 +108,7 @@ func (s *UserStorage) GetByProvider(provider string, uid string) (*models.User,
AND up.provider_uid = $2
AND u.tenant_id = $3`
if err := s.trx.Scalar(&userID, query, provider, uid, s.tenant.ID); err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get user by provider '%s' and uid '%s'", provider, uid)
}
return s.GetByID(userID)
}
@@ -111,12 +120,12 @@ func (s *UserStorage) Register(user *models.User) error {
if err := s.trx.Get(&user.ID,
"INSERT INTO users (name, email, created_on, tenant_id, role) VALUES ($1, $2, $3, $4, $5) RETURNING id",
user.Name, user.Email, now, s.tenant.ID, user.Role); err != nil {
- return err
+ return errors.Wrap(err, "failed to register new user")
}
for _, provider := range user.Providers {
if _, err := s.trx.Execute("INSERT INTO user_providers (tenant_id, user_id, provider, provider_uid, created_on) VALUES ($1, $2, $3, $4, $5)", s.tenant.ID, user.ID, provider.Name, provider.UID, now); err != nil {
- return err
+ return errors.Wrap(err, "failed to add provider to new user")
}
}
@@ -127,14 +136,20 @@ func (s *UserStorage) Register(user *models.User) error {
func (s *UserStorage) RegisterProvider(userID int, provider *models.UserProvider) error {
cmd := "INSERT INTO user_providers (tenant_id, user_id, provider, provider_uid, created_on) VALUES ($1, $2, $3, $4, $5)"
_, err := s.trx.Execute(cmd, s.tenant.ID, userID, provider.Name, provider.UID, time.Now())
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to add provider '%s' to user with id '%d'", provider.Name, userID)
+ }
+ return nil
}
// Update user profile
func (s *UserStorage) Update(settings *models.UpdateUserSettings) error {
cmd := "UPDATE users SET name = $2 WHERE id = $1 AND tenant_id = $3"
_, err := s.trx.Execute(cmd, s.user.ID, settings.Name, s.tenant.ID)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to update user")
+ }
+ return nil
}
// UpdateSettings of given user
@@ -148,7 +163,7 @@ func (s *UserStorage) UpdateSettings(settings map[string]string) error {
for key, value := range settings {
_, err := s.trx.Execute(query, s.tenant.ID, s.user.ID, key, value)
if err != nil {
- return err
+ return errors.Wrap(err, "failed to update user settings")
}
}
}
@@ -165,7 +180,7 @@ func (s *UserStorage) GetUserSettings() (map[string]string, error) {
var settings []*dbUserSetting
err := s.trx.Select(&settings, "SELECT key, value FROM user_settings WHERE user_id = $1 AND tenant_id = $2", s.user.ID, s.tenant.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get user settings")
}
var result = make(map[string]string, len(settings))
@@ -188,14 +203,20 @@ func (s *UserStorage) GetUserSettings() (map[string]string, error) {
func (s *UserStorage) ChangeRole(userID int, role models.Role) error {
cmd := "UPDATE users SET role = $3 WHERE id = $1 AND tenant_id = $2"
_, err := s.trx.Execute(cmd, userID, s.tenant.ID, role)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to change user's role")
+ }
+ return nil
}
// ChangeEmail of given user
func (s *UserStorage) ChangeEmail(userID int, email string) error {
cmd := "UPDATE users SET email = $3 WHERE id = $1 AND tenant_id = $2"
_, err := s.trx.Execute(cmd, userID, s.tenant.ID, email)
- return err
+ if err != nil {
+ return errors.Wrap(err, "failed to update user's email")
+ }
+ return nil
}
// GetByID returns a user based on given id
@@ -219,7 +240,7 @@ func (s *UserStorage) GetAll() ([]*models.User, error) {
var users []*dbUser
err := s.trx.Select(&users, "SELECT id, name, email, tenant_id, role FROM users WHERE tenant_id = $1 ORDER BY id", s.tenant.ID)
if err != nil {
- return nil, err
+ return nil, errors.Wrap(err, "failed to get all users")
}
var result = make([]*models.User, len(users))
@@ -237,11 +258,11 @@ func (s *UserStorage) HasSubscribedTo(ideaID int) (bool, error) {
var status int
err := s.trx.Scalar(&status, "SELECT status FROM idea_subscribers WHERE user_id = $1 AND idea_id = $2", s.user.ID, ideaID)
- if err != nil && err != app.ErrNotFound {
- return false, err
+ if err != nil && errors.Cause(err) != app.ErrNotFound {
+ return false, errors.Wrap(err, "failed to get subscription status")
}
- if err == app.ErrNotFound {
+ if errors.Cause(err) == app.ErrNotFound {
for _, e := range models.AllNotificationEvents {
for _, r := range e.RequiresSubscripionUserRoles {
if r == s.user.Role {
diff --git a/app/storage/postgres/user_test.go b/app/storage/postgres/user_test.go
index 68b8858d2..b501f34fe 100644
--- a/app/storage/postgres/user_test.go
+++ b/app/storage/postgres/user_test.go
@@ -5,6 +5,7 @@ import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/oauth"
. "github.com/onsi/gomega"
)
@@ -73,7 +74,7 @@ func TestUserStorage_GetByProvider_WrongTenant(t *testing.T) {
users.SetCurrentTenant(avengersTenant)
user, err := users.GetByProvider("facebook", "FB1234")
Expect(user).To(BeNil())
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
}
func TestUserStorage_GetByEmail_WrongTenant(t *testing.T) {
@@ -234,7 +235,7 @@ func TestUserStorage_ChangeEmail(t *testing.T) {
Expect(user.Email).To(Equal("[email protected]"))
user, err = users.GetByEmail("[email protected]")
- Expect(err).To(Equal(app.ErrNotFound))
+ Expect(errors.Cause(err)).To(Equal(app.ErrNotFound))
Expect(user).To(BeNil())
}
diff --git a/app/tasks/tasks.go b/app/tasks/tasks.go
index 69b61b120..de7d6a78e 100644
--- a/app/tasks/tasks.go
+++ b/app/tasks/tasks.go
@@ -67,21 +67,21 @@ func NotifyAboutNewIdea(idea *models.Idea) worker.Task {
// Web notification
users, err := c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelWeb, models.NotificationEventNewIdea)
if err != nil {
- return err
+ return c.Failure(err)
}
title := fmt.Sprintf("New idea: **%s**", idea.Title)
link := fmt.Sprintf("/ideas/%d/%s", idea.Number, idea.Slug)
for _, user := range users {
if _, err = c.Services().Notifications.Insert(user, title, link, idea.ID); err != nil {
- return err
+ return c.Failure(err)
}
}
// Email notification
users, err = c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelEmail, models.NotificationEventNewIdea)
if err != nil {
- return err
+ return c.Failure(err)
}
to := make([]email.Recipient, 0)
@@ -108,21 +108,21 @@ func NotifyAboutNewComment(idea *models.Idea, comment *models.NewComment) worker
// Web notification
users, err := c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelWeb, models.NotificationEventNewComment)
if err != nil {
- return err
+ return c.Failure(err)
}
title := fmt.Sprintf("**%s** left a comment on **%s**", c.User().Name, idea.Title)
link := fmt.Sprintf("/ideas/%d/%s", idea.Number, idea.Slug)
for _, user := range users {
if _, err = c.Services().Notifications.Insert(user, title, link, idea.ID); err != nil {
- return err
+ return c.Failure(err)
}
}
// Email notification
users, err = c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelEmail, models.NotificationEventNewComment)
if err != nil {
- return err
+ return c.Failure(err)
}
to := make([]email.Recipient, 0)
@@ -155,28 +155,28 @@ func NotifyAboutStatusChange(idea *models.Idea, response *models.SetResponse) wo
// Web notification
users, err := c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelWeb, models.NotificationEventChangeStatus)
if err != nil {
- return err
+ return c.Failure(err)
}
title := fmt.Sprintf("**%s** changed status of **%s** to **%s**", c.User().Name, idea.Title, models.GetIdeaStatusName(response.Status))
link := fmt.Sprintf("/ideas/%d/%s", idea.Number, idea.Slug)
for _, user := range users {
if _, err = c.Services().Notifications.Insert(user, title, link, idea.ID); err != nil {
- return err
+ return c.Failure(err)
}
}
// Email notification
users, err = c.Services().Ideas.GetActiveSubscribers(idea.Number, models.NotificationChannelEmail, models.NotificationEventChangeStatus)
if err != nil {
- return err
+ return c.Failure(err)
}
var duplicate template.HTML
if response.Status == models.IdeaDuplicate {
originalIdea, err := c.Services().Ideas.GetByNumber(response.OriginalNumber)
if err != nil {
- return err
+ return c.Failure(err)
}
duplicate = linkWithText(originalIdea.Title, c.BaseURL(), "/ideas/%d/%s", originalIdea.Number, originalIdea.Slug)
}