zoukankan      html  css  js  c++  java
  • 17.统一异常处理(下),设置自己的Error对象

    自定义错误结构体

    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)
            }
        }
    }
    




  • 相关阅读:
    2016年10月30日表单标签与样式表分类和选择器
    2016年10月29日常用标签与表格
    2016年10月28日网页属性和通用标签
    10月27日体会目标
    字符串学习笔记
    [51nod1789] 跑得比谁都快
    [洛谷9月月赛]签到题
    [LUOGU2730] 魔板
    [SCOI2009]迷路
    [51nod1074] 约瑟夫问题 V2
  • 原文地址:https://www.cnblogs.com/hualou/p/12083600.html
Copyright © 2011-2022 走看看