定义错误
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
转载于:https://blog.51cto.com/5660061/2348033