goang 错误&异常处理机制

作者: 火头陀 | 来源:发表于2018-09-30 00:16 被阅读15次

基本概念

  • 错误:意料之内,可能出的问题, 比如网络连接超时,json解析错误等
  • 异常:意料之外,不应该出的问题,比如空指针异常,下标溢出等异常

错误处理

golang 使用error接口作为标准错误接口,

通常情况下错误处理方式

if err != nil{
    //错误处理逻辑
}

error作为函数返回值时应该放在最后一个返回值:eg:

func get()(res string, err error){
    return
}

使用error作为返回值的规范是函数体内有可能产生多种错误时返回error,当仅有一种error的可能或者类型时应该用bool类型代替,这样更简洁,eg:

//此方法种只有一种逻辑上的错误,不应该返回error, 推荐使用checkNumAreaB函数的写法
func checkNumArea(num int) error {
    if num > 100{
        return errors.New("超出值域")
    }
    return nil
}

func checkNumAreaB(num int) bool {
    if num > 100{
        return false
    }
    return true
}

异常处理

The panic built-in function stops normal execution of the current goroutine. When a function F calls panic, normal execution of F stops immediately. Any functions whose execution was deferred by F are run in the usual way, and then F returns to its caller. To the caller G, the invocation of F then behaves like a call to panic, terminating G's execution and running any deferred functions. This continues until all functions in the executing goroutine have stopped, in reverse order. At that point, the program is terminated and the error condition is reported, including the value of the argument to panic. This termination sequence is called panicking and can be controlled by the built-in function recover.

从官方介绍可知panic调用会使整个调用栈逆序终止,最终导致整个程序终止并输出调中栈信息, 可使用recover方法捕获异常而避免程序终结,生产环境种必须有此操作以避免程序终止

panic类似java的throw python的raise, recover 类似try catch

常用处理方式如下

func A(){
    defer func(){
       fmt.Println("3") 
    }()
    defer func(){
        if err := recover(); err != nil{
            fmt.Println("err:", err)
        }
    }()
    
    panic("1")
    fmt.Println("2")
}
A()
//outout:
//err:1
//3
  • defer的执行逻辑时LIFO,
  • defer的执行是在函数执行完毕,return,panic之后的
  • panic之后的逻辑不再执行

相关文章

网友评论

    本文标题:goang 错误&异常处理机制

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