Skip to content

Commit

Permalink
refactor: ErrUnsupportedSerialization 支持 errors.ErrUnsupported
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Nov 23, 2023
1 parent c3d1298 commit f17bd02
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 20 deletions.
10 changes: 5 additions & 5 deletions app/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,23 +138,23 @@ func (cert *certificateConfig) sanitize() *web.FieldError {

func (h *httpConfig) sanitize() *web.FieldError {
if h.ReadTimeout < 0 {
return web.NewFieldError("readTimeout", locales.ShouldGreatThanZero)
return web.NewFieldError("readTimeout", locales.ShouldGreatThan(0))
}

if h.WriteTimeout < 0 {
return web.NewFieldError("writeTimeout", locales.ShouldGreatThanZero)
return web.NewFieldError("writeTimeout", locales.ShouldGreatThan(0))
}

if h.IdleTimeout < 0 {
return web.NewFieldError("idleTimeout", locales.ShouldGreatThanZero)
return web.NewFieldError("idleTimeout", locales.ShouldGreatThan(0))
}

if h.ReadHeaderTimeout < 0 {
return web.NewFieldError("readHeaderTimeout", locales.ShouldGreatThanZero)
return web.NewFieldError("readHeaderTimeout", locales.ShouldGreatThan(0))
}

if h.MaxHeaderBytes < 0 {
return web.NewFieldError("maxHeaderBytes", locales.ShouldGreatThanZero)
return web.NewFieldError("maxHeaderBytes", locales.ShouldGreatThan(0))
}

if h.RequestID == "" {
Expand Down
4 changes: 2 additions & 2 deletions cmd/web/enum/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (t *Type) dump(buf *errwrap.Buffer) {
Printf("if v,found := %s[%s];found{\n", t.type2StringMapName, t.receiver).
WString("return []byte(v),nil\n").
WString("}\n").
Printf(`return []byte(fmt.Sprintf("%s(%%d)", %s)),web.NewLocaleError("invalid value")`, t.name, t.receiver).WRune('\n').
Printf(`return []byte(fmt.Sprintf("%s(%%d)", %s)),locales.ErrInvalidValue()`, t.name, t.receiver).WRune('\n').
WString("}\n\n")

// Parse
Expand All @@ -93,7 +93,7 @@ func (t *Type) dump(buf *errwrap.Buffer) {
Printf("if t,found := %s[v];found{\n", t.string2TypeMapName).
WString("return t,nil\n").
WString("}\n").
WString(`return 0,web.NewLocaleError("invalid value")`).WRune('\n').
WString(`return 0,locales.ErrInvalidValue()`).WRune('\n').
WString("}\n\n")

// TextUnmarshaler
Expand Down
21 changes: 21 additions & 0 deletions codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package web

import (
"errors"
"fmt"
"io"
"strings"
Expand All @@ -15,6 +16,10 @@ import (
"github.com/issue9/web/internal/header"
)

var errUnsupportedSerialization = errorUnsupportedSerialization{}

type errorUnsupportedSerialization struct{}

// Codec 编码解码工具
//
// 包含了压缩方法和媒体类型的处理
Expand Down Expand Up @@ -69,6 +74,22 @@ type compression struct {
wildcardSuffix []string
}

func (err errorUnsupportedSerialization) Error() string {
return err.LocaleString(nil)
}

func (err errorUnsupportedSerialization) LocaleString(p *localeutil.Printer) string {
return StringPhrase("unsupported serialization").LocaleString(p)
}

func (err errorUnsupportedSerialization) Unwrap() error { return errors.ErrUnsupported }

// ErrUnsupportedSerialization 返回不支持序列化的错误信息
//
// 此方法的返回对象同时也包含了 [errors.ErrUnsupported],
// errors.Is(ErrUnsupportedSerialization(), errors.ErrUnsupported) == true。
func ErrUnsupportedSerialization() error { return errUnsupportedSerialization }

func buildCompression(c Compressor, types []string) *compression {
m := &compression{compressor: c}

Expand Down
8 changes: 8 additions & 0 deletions codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"compress/gzip"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"testing"
Expand Down Expand Up @@ -341,3 +342,10 @@ func TestCodec_findMarshal(t *testing.T) {
item = mm.findMarshal("xx/*")
a.Nil(item)
}

func TestUnsupportedSerialization(t *testing.T) {
a := assert.New(t, false)

a.ErrorIs(ErrUnsupportedSerialization(), errors.ErrUnsupported)
a.Equal(ErrUnsupportedSerialization().Error(), "unsupported serialization")
}
4 changes: 2 additions & 2 deletions input.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func (p *Paths) ID(key string) int64 {
p.filter().AddError(key, err)
return 0
} else if id <= 0 {
p.filter().AddReason(key, locales.ShouldGreatThanZero)
p.filter().AddReason(key, locales.ShouldGreatThan(0))
return 0
}
return id
Expand Down Expand Up @@ -121,7 +121,7 @@ func (ctx *Context) PathID(key, id string) (int64, Problem) {
if err != nil {
return 0, ctx.Problem(id).WithParam(key, Phrase(err.Error()).LocaleString(p))
} else if ret <= 0 {
return 0, ctx.Problem(id).WithParam(key, locales.ShouldGreatThanZero.LocaleString(p))
return 0, ctx.Problem(id).WithParam(key, locales.ShouldGreatThan(0).LocaleString(p))
}
return ret, nil
}
Expand Down
15 changes: 14 additions & 1 deletion locales/locales.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,23 @@ var All = []fs.FS{

// 一些多处用到的翻译项
const (
ShouldGreatThanZero = localeutil.StringPhrase("should great than 0")
InvalidValue = localeutil.StringPhrase("invalid value")
CanNotBeEmpty = localeutil.StringPhrase("can not be empty")
DuplicateValue = localeutil.StringPhrase("duplicate value")
UniqueIdentityGenerator = localeutil.StringPhrase("unique identity generator")
RecycleLocalCache = localeutil.StringPhrase("recycle local cache")
)

// ShouldGreatThan 返回必须大于 n 的翻译项
func ShouldGreatThan(n int) localeutil.Stringer {
return localeutil.Phrase("should great than %d", n)
}

var (
errInvalidValue = localeutil.Error("invalid value")
errCanNotBeEmpty = localeutil.Error("can not be empty")
)

func ErrInvalidValue() error { return errInvalidValue }

func ErrCanNotBeEmpty() error { return errCanNotBeEmpty }
4 changes: 2 additions & 2 deletions locales/und.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -291,9 +291,9 @@ messages:
- key: scheduler jobs
message:
msg: scheduler jobs
- key: should great than 0
- key: should great than %d
message:
msg: should great than 0
msg: should great than %d
- key: the client miss content-type header
message:
msg: the client miss content-type header
Expand Down
4 changes: 2 additions & 2 deletions locales/zh-CN.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -307,9 +307,9 @@ messages:
- key: scheduler jobs
message:
msg: 计划任务
- key: should great than 0
- key: should great than %d
message:
msg: 必须大于 0
msg: 必须大于 %d
- key: the client miss content-type header
message:
msg: 客户端未指定 Content-Type 报头
Expand Down
2 changes: 1 addition & 1 deletion problem.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ type (

// WithInstance 指定发生错误的实例
//
// 多次调用将会覆盖之前的内容。
// 多次调用将会覆盖之前的内容。默认为 [Context.ID]。
WithInstance(string) Problem

// 不允许其它实现
Expand Down
5 changes: 0 additions & 5 deletions web.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ const (
Failed = scheduled.Failed // 出错,不再执行后续操作
)

var errUnsupportedSerialization = NewLocaleError("unsupported serialization")

type (
Logger = logs.Logger
Logs = logs.Logs
Expand Down Expand Up @@ -111,9 +109,6 @@ type (
// NewCache 声明带有统一前缀的缓存接口
func NewCache(prefix string, c Cache) Cache { return cache.Prefix(c, prefix) }

// ErrUnsupportedSerialization 返回不支持序列化的错误信息
func ErrUnsupportedSerialization() error { return errUnsupportedSerialization }

func (f ServiceFunc) Serve(ctx context.Context) error { return f(ctx) }

// Phrase 生成本地化的语言片段
Expand Down

0 comments on commit f17bd02

Please sign in to comment.