go 错误处理
定义错误示例
package main
import (
"errors"
"fmt"
)
var errNotFound error = errors.New("Not found error")
func main() {
fmt.Printf("error: %v", errNotFound)
}
自定义错误示例
package main
import (
"fmt"
"os"
"time"
)
type PathError struct {
path string
op string
createTime string
message string
}
func (p *PathError) Error() string {
return fmt.Sprintf("path=%s op=%s createTime=%s message=%s", p.path,
p.op, p.createTime, p.message)
}
func Open(filename string) error {
file, err := os.Open(filename)
if err != nil {
return &PathError{
path: filename,
op: "read",
message: err.Error(),
createTime: fmt.Sprintf("%v", time.Now()),
}
}
defer file.Close()
return nil
}
func main() {
err := Open("C:/asdf.txt")
switch v := err.(type) {
case *PathError:
fmt.Println("get path error,", v)
default:
}
}

panic和recover
package main
import (
"log"
"github.com/StackExchange/wmi"
"fmt"
)
type WinBattery struct {
Status string
Name string
DeviceID string
EstimatedRunTime uint32
EstimatedChargeRemaining uint16
test string
}
func Win32Battery(s *[]WinBattery) {
err := wmi.Query("SELECT * FROM Win32_Battery WHERE (Status IS NOT NULL)", s)
if err != nil {
panic(err)
}
}
func f() {
b()
}
func b() {
win32 := &[]WinBattery{}
Win32Battery(win32)
fmt.Println(win32)
}
func main() {
defer func() {
if r := recover(); r != nil {
log.Printf("Runtime error caught: %v", r)
}
}()
f()
}
Golang 有2个内置的函数 panic() 和 recover(),用以报告和捕获运行时发生的程序错误,与 error 不同,panic-recover 一般用在函数内部。
golang 的错误处理流程:当一个函数在执行过程中出现了异常或遇到 panic(),正常语句就会立即终止,然后执行 defer 语句,再报告异常信息,最后退出 goroutine。如果在 defer 中使用了 recover() 函数,则会捕获错误信息,使该错误信息终止报告。
参考博文:https://www.flysnow.org/2019/01/01/golang-error-handle-suggestion.html