自定义错误结构体
package utils
type MyError struct {
Code int
Message string
}
func NewMyError(code int, msg string) error {
return &MyError{Code: code, Message: msg}
}
func (this *MyError) Error() string {
return this.Message
}
如何处理我们自定义的Error
func MyErrorEncoder(ctx context.Context, err error, w http.ResponseWriter) {
contentType, body := "text/plain; charset=utf-8", []byte(err.Error())
w.Header().Set("Content-type", contentType) //设置请求头
if myerr, ok := err.(*utils.MyError); ok { //通过类型断言判断当前error的类型,走相应的处理
w.WriteHeader(myerr.Code)
w.Write(body)
} else {
w.WriteHeader(500)
w.Write(body)
}
}
调用自定义结构体
func RateLimit(limit *rate.Limiter) endpoint.Middleware { //Middleware type Middleware func(Endpoint) Endpoint
return func(next endpoint.Endpoint) endpoint.Endpoint { //Endpoint type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error)
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
if !limit.Allow() {
return nil, utils.NewMyError(429, "toot many request") //使用我们自定的错误结构体
}
return next(ctx, request)
}
}
}