Go~实现自定义Error返回体
error接口
假设你就已经创建和使用过神秘的预定义error类型,但是没有解释它究竟是什么。实际上它就是interface类型,这个类型有一个返回错误信息的单一方法:
// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface {
Error() string
}
创建一个error最简单的方法就是调用errors.New函数,它会根据传入的错误信息返回一个新的error。
调用errors.New函数是非常稀少的,因为有一个方便的封装函数fmt.Errorf,它还会处理字符串格式化。
func Errorf(format string, args ...interface{}) error {
return errors.New(Sprintf(format, args...))
}
- 那如果我们想自定义一个error自然实现这个error接口即可
自定义error
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 \nop=%s \ncreateTime=%s \nmessage=%s", p.path,
p.op, p.createTime, p.message)
}
func Open(filename string) error {
file, err := os.Open(filename)
if err != nil {
// 返回自定义error
return &PathError{
path: filename,
op: "read",
message: err.Error(),
createTime: fmt.Sprintf("%v", time.Now()),
}
}
defer file.Close()
return nil
}
func main() {
err := Open("/Users/5lmh/Desktop/go/src/test.txt")
// 判断error类型
switch v := err.(type) {
case *PathError:
fmt.Println("get path error,", v)
default:
fmt.Println("other error,", v)
}
}
get path error, path=/Users/5lmh/Desktop/go/src/test.txt op=read
createTime=2022-03-27 10:49:34.1425917 +0800 CST m=+0.004917201
message=open /Users/5lmh/Desktop/go/src/test.txt: The system cannot
find the path specified.