[golang] 錯誤處理

[golang] 錯誤處理

Go語言的錯誤處理方式

Go語言 提供了兩種錯誤處理方式:

  • 返回錯誤模式: 函數的返回是一個複合類型,其中一個類型(習慣上是最後一個類型)是 error ,類似於:(, error)

這種模式被期望處理的場景是:當錯誤發生的情況下,在處理錯誤後,程序扔可以繼續執行下去。

  • 中斷/恢復模式:panic/recover

中斷/恢復模式適用於:當錯誤發生的情況下,處理錯誤後,程序無法繼續執行下去,需要中斷當前的程序或者協程。

error 接口

Go語言提供了內嵌接口 error,其定義是:

type error interface {
    Error() string
}

因此,任何有 Error() string 方法的類型都可以被認爲是Error類。

type PathError struct {
	Op   string // "open", "unlink", etc.
	Path string // The associated file.
}

func (e *PathError) Error() string {
	return e.Op + " " + e.Path
}

error 返回/處理模式

Go語言中, 當一個錯誤發生時,希望處理這個錯誤,然後繼續執行。因此默認的錯誤處理模式是返回包含錯誤變量的複合結果。

func returnError() (ret interface{}, err error) {
	return nil, &PathError{Op: "open", Path: "/root"}
}


func main() {
	_, err := returnError()
	if err != nil {
		...
	}

}

panic 和 recover

當錯誤發生時,程序無法執行下去的時候,這時期望終止程序或者終止當前的協程,在這種情況下,Go語言提供了內嵌函數 panic

panic 函數的參數可以是任何類型,一般會使用 string

recover 用於在上層抓住 panic 中的參數,並做適當的處理。

有趣的是,panic()/recover()有點兒像是 try/catch

示例:

package main

import "fmt"

// PathError records an error and the operation and
// file path that caused it.
type PathError struct {
	Op   string // "open", "unlink", etc.
	Path string // The associated file.
}

func (e *PathError) Error() string {
	return e.Op + " " + e.Path
}

func main() {
	defer func() {
		if e := recover(); e != nil {
			fmt.Println(e)
		}
	}()
	_, err := returnError()
	if err != nil {
		panic(err.Error())
	}

}

func returnError() (ret interface{}, err error) {
	return nil, &PathError{Op: "open", Path: "/root"}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章