话不多说,先上GO实现Error的源码
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package errors implements functions to manipulate errors.
// error 包实现了用于错误处理的函数.
package errors
// New returns an error that formats as the given text.
// New 返回一个按给定文本格式化的错误。
func New(text string) error {
return &errorString{text}
}
// errorString is a trivial implementation of error.
// errorString 是 error 的一个琐碎的实现。
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
自定义处理
package main
import (
"fmt"
"time"
)
type MyError struct{
When time.Time
What string
}
func (e MyError) Error() string {
return fmt.Sprintf("%v:%v",e.When , e.What)
}
func oops() error {
return MyError{
time.Now(),
"Error Example",
}
}
func main() {
if err := oops(); err != nil {
fmt.Println(err)
}
}