美文网首页
golang-统一异常处理

golang-统一异常处理

作者: 爱吃豆包 | 来源:发表于2019-12-17 20:31 被阅读0次

    在我们意料中的,使用 error, 意料之外的用 panic

    异常分为系统异常, 和 业务异常!
    业务异常是可以抛给用户看的,系统异常是我们自己处理的!

    // 自定义异常
    // 定义一个 UserError 接口
    type UserError interface {
        error
        Message() string
    }
    
    
    
    

    里一个地方实现了 上面的 UserError 异常接口

    // 实现 UserError 接口
    type UserError string
    
    // 实现 UserError 接口 里面的方法
    func (e UserError) Error() string {
        return e.Message()
    }
    
    // 实现 UserError 接口 里面的方法
    func (e UserError) Message() string {
        return string(e)
    }
    
    

    这一个例子,使用了异常捕获!
    业务异常是可以抛给用户看的,系统异常是我们自己处理的!
    UserError 是我们的业务异常

    // 声明一个函数类型
    // 这样是声明的函数只是一个占位用
    type appHandel func(writer http.ResponseWriter, request *http.Request) error
    
    
    // 函数式编程
    func errWrapper (handel appHandel) func(writer http.ResponseWriter, request *http.Request)  {
    
        // 函数式编程,必须return 函数类型, 因为我的返回值就是函数
        return func(writer http.ResponseWriter, request *http.Request) {
    
            // 捕获异常
            defer func() {
                if r := recover(); r != nil {
                    log.Panicf("Panic: %v", r)
                    http.Error(writer, http.StatusText(http.StatusInternalServerError),
                        http.StatusInternalServerError)
                }
    
            }()
    
    
            err := handel(writer, request)
            if err != nil {
    
                // 如果是我们自己异常,就展示给用户看
                if userError, ok := err.(UserError); ok {
                    http.Error(writer, userError.Message(), http.StatusBadRequest)
                    return
                }
    
                code := http.StatusOK
                switch {
                case os.IsNotExist(err): // 如果是文件不存在类型
                    // 如果是文件不存在
                    // 给出403 响应
                    code = http.StatusForbidden
                default:
                    code = http.StatusInternalServerError
                }
    
                http.Error(writer, "文件不存在", code)
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:golang-统一异常处理

          本文链接:https://www.haomeiwen.com/subject/izuenctx.html