码迷,mamicode.com
首页 > 其他好文 > 详细

错误处理

时间:2019-01-31 01:25:31      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:ret   imp   spec   fun   error   sdk   defer   roc   print   

定义错误

package main

import (
    "errors"
    "fmt"
)

var errNotFound error = errors.New("Not found error")

func main() {
    fmt.Printf("error: %v", errNotFound)
}

自定义错误

type error interface { 
        Error() string 
} 

自定义错误

package main
import (
//  "fmt"
)
type PathError struct {
    Op   string
    Path string
    err string
}
func (e *PathError) Error() string {
    return e.Op + " " + e.Path + ": " + e.Err.Error()
}
func test() error {
    return &PathError{
        Op:   "op",
        Path: "path",
    }
}
func main() {
    test()
}

如何判断自定义错误

switch err := err.(type) {
case ParseError:
         PrintParseError(err)
case PathError:
         PrintPathError(err)
... default: 
} 

Panic&Recover

package main

import (
    "fmt"
)

func badCall() {
    panic("bad end")
}

func test() {
    defer func() {
        if e := recover(); e != nil {
            fmt.Printf("Panicking %s\r\n", e)
        }
    }()
    badCall()
    fmt.Printf("After bad call\r\n")
}

func main() {
    fmt.Printf("Calling test\r\n")
    test()
    fmt.Printf("Test completed\r\n")
}

错误自定义例子:

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:/sdklflakfljdsafjs.txt")
    switch v := err.(type) {
    case *PathError:
        fmt.Println("get path error,", v)
    default:

    }

}

输出:
get path error, path=C:/sdklflakfljdsafjs.txt op=read createTime=2019-01-31 00:21:56.0078036 +0800 CST m=+0.043956001 message=open C:/sdklflakfljdsafjs.txt: The system cannot find the file specified.

Process finished with exit code 0

错误处理

标签:ret   imp   spec   fun   error   sdk   defer   roc   print   

原文地址:http://blog.51cto.com/5660061/2348033

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!