refactor: user error system (#40308)

Introduce "FlashErrorAuto" for "XxxErrorAuto" family and simplify the
error handling logic.

* Use ErrorUnwrapForHTML for web error messages 
* Use ErrorUnwrapForUser for api error messages
* Make Flash message can take up to about 3000 bytes

Next step: completely refactor "ctx.ServerError"

---------

Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
wxiaoguangandsilverwind authored and GitHub committed 2026-11-10 16:29:36 +00:00
1 parent 518e08c2c7
commit d1d702bea9
20 files changed
+309 -194

No files matched your search

+51 -32
View File
@@ -6,6 +6,7 @@ package util
import (
"errors"
"fmt"
"html"
"html/template"
)
@@ -13,13 +14,6 @@ import (
// These errors can be used to classify errors and to provide a common,
// safe (no server-side sensitive information), and translatable error message for end users.
// ErrorTranslatable wraps an error with translation information
type ErrorTranslatable interface {
error
Unwrap() error
Translate(ErrorLocaleTranslator) template.HTML
}
var (
ErrInvalidArgument = errorForUser{400, "invalid argument"}
ErrPermissionDenied = errorForUser{403, "permission denied"}
@@ -40,7 +34,48 @@ func (w errorForUser) Error() string {
return w.msg
}
// TODO: introduce ErrorUnwrapForHTML in the future for web error rendering
// ErrorTranslateHTML translates the error message to HTML using the provided locale translator.
// If the error is not translatable, it returns false.
func ErrorTranslateHTML(err error, locale ErrorLocaleTranslator) (template.HTML, bool) {
if errAs := errorAsTranslatable(err); errAs != nil {
return locale.Tr(errAs.trKey, errAs.trArgs...), true
}
return "", false
}
// ErrorUnwrapForHTML unwraps the user error and returns the error message in HTML format and the HTTP status code.
// An error is considered a user error if it is "errorForUser" or "errorTranslatable"
// * errorTranslatable: The error message is translated to HTML using the provided locale translator.
// * errorForUser: The error message is returned as is (escaped to HTML) and the HTTP status code is returned.
// If the error is not a user error, it returns an empty message and code 0.
func ErrorUnwrapForHTML(err error, locale ErrorLocaleTranslator) (msg template.HTML, code int) {
if e, ok := errors.AsType[errorForUser](err); ok {
code = e.code
}
if htmlMsg, ok := ErrorTranslateHTML(err, locale); ok {
msg = htmlMsg
code = IfZero(code, 400)
}
if code != 0 && msg == "" {
errMsg := err.Error()
switch errMsg {
case ErrPermissionDenied.msg:
msg = locale.Tr("error.permission_denied")
case ErrNotExist.msg:
msg = locale.Tr("error.not_found")
default:
msg = template.HTML(html.EscapeString(errMsg))
}
}
return msg, code
}
// ErrorUnwrapForUser unwraps the user error and returns the error message in string format and the HTTP status code.
// It is mainly used for API error responses, and ideally only English locale should be used.
//
// It also accepts a locale translator to translate the error message if it is translatable:
// * for example: there are different error messages for "ErrBlockedUser": blocked by owner, or blocked by assignee
// * only the function returned the error message can know the exact reason
func ErrorUnwrapForUser(err error, locale ...ErrorLocaleTranslator) (msg string, code int) {
e, ok := errors.AsType[errorForUser](err)
if ok {
@@ -98,7 +133,7 @@ func NewNotExistErrorf(message string, args ...any) error {
return ErrorWrap(ErrNotExist, message, args...)
}
type errorTranslatableWrapper struct {
type errorTranslatable struct {
err error
trKey string
trArgs []any
@@ -109,30 +144,14 @@ type ErrorLocaleTranslator interface {
TrString(key string, args ...any) string
}
func (w *errorTranslatableWrapper) Error() string { return w.err.Error() }
func (w *errorTranslatable) Error() string { return w.err.Error() }
func (w *errorTranslatable) Unwrap() error { return w.err }
func (w *errorTranslatableWrapper) Unwrap() error { return w.err }
func (w *errorTranslatableWrapper) Translate(t ErrorLocaleTranslator) template.HTML {
return t.Tr(w.trKey, w.trArgs...)
func ErrorWrapTranslatable(err error, trKey string, trArgs ...any) error {
return &errorTranslatable{err: err, trKey: trKey, trArgs: trArgs}
}
func ErrorWrapTranslatable(err error, trKey string, trArgs ...any) ErrorTranslatable {
return &errorTranslatableWrapper{err: err, trKey: trKey, trArgs: trArgs}
}
func errorAsTranslatable(err error) *errorTranslatableWrapper {
if e, ok := errors.AsType[*errorTranslatableWrapper](err); ok {
return e
}
return nil
}
// TODO: refactor ErrorAsTranslatable in the future, use ErrorUnwrapForUser or ErrorUnwrapForHTML as much as possible
func ErrorAsTranslatable(err error) ErrorTranslatable {
e := errorAsTranslatable(err)
if e != nil { // avoid golang nil interface wrapper
return e
}
return nil
func errorAsTranslatable(err error) *errorTranslatable {
e, _ := errors.AsType[*errorTranslatable](err)
return e
}
+30 -8
View File
@@ -5,6 +5,7 @@ package util
import (
"fmt"
"html/template"
"io"
"testing"
@@ -18,7 +19,7 @@ func TestErrorTranslatable(t *testing.T) {
err = ErrorWrapTranslatable(io.EOF, "key", 1)
assert.ErrorIs(t, err, io.EOF)
assert.Equal(t, "EOF", err.Error())
wrapped, ok := err.(*errorTranslatableWrapper)
wrapped, ok := err.(*errorTranslatable)
require.True(t, ok)
assert.Equal(t, "key", wrapped.trKey)
assert.Equal(t, []any{1}, wrapped.trArgs)
@@ -26,15 +27,36 @@ func TestErrorTranslatable(t *testing.T) {
err = ErrorWrap(err, "new msg %d", 100)
assert.ErrorIs(t, err, io.EOF)
assert.Equal(t, "new msg 100", err.Error())
}
errTr := ErrorAsTranslatable(err)
assert.Equal(t, "EOF", errTr.Error())
wrapped, ok = errTr.(*errorTranslatableWrapper)
require.True(t, ok)
assert.Equal(t, "key", wrapped.trKey)
type testErrorLocale struct{}
errTr = ErrorAsTranslatable(nil)
assert.True(t, errTr == nil) //nolint:testifylint // assert golang nil interface wrapper
func (l testErrorLocale) Tr(key string, args ...any) template.HTML {
return template.HTML(l.TrString(key, args...))
}
func (testErrorLocale) TrString(key string, args ...any) string {
return fmt.Sprintf(key, args...)
}
func TestErrorUnwrapForHTML(t *testing.T) {
locale := testErrorLocale{}
err := NewNotExistErrorf("missing <file>")
msg, code := ErrorUnwrapForHTML(err, locale)
assert.Equal(t, template.HTML("missing &lt;file&gt;"), msg)
assert.Equal(t, 404, code)
msg, code = ErrorUnwrapForHTML(ErrorWrapTranslatable(err, "missing <b>%s</b>", "file"), locale)
assert.Equal(t, template.HTML("missing <b>file</b>"), msg)
assert.Equal(t, 404, code)
msg, code = ErrorUnwrapForHTML(ErrorWrapTranslatable(io.EOF, "unexpected end of input"), locale)
assert.Equal(t, template.HTML("unexpected end of input"), msg)
assert.Equal(t, 400, code)
msg, code = ErrorUnwrapForHTML(io.EOF, locale)
assert.Empty(t, msg)
assert.Zero(t, code)
}
func TestErrorUnwrapForUser(t *testing.T) {