首页 > 其他 > 详细

A Tour of Go Errors

时间:2014-10-28 21:34:50      阅读:257      评论:0      收藏:0      [点我收藏+]

An error is anything that can describe itself as an error string. The idea is captured by the predefined, built-in interface type, error, with its single method, Error, returning a string:

type error interface {
    Error() string
}

The fmt package‘s various print routines automatically know to call the method when asked to print an error.

package main  

import (
    "fmt"
    "time"
)

type MyError struct {
    When time.Time 
    What string
}

func (e *MyError) Error() string {
    return fmt.Sprintf("at %v, %s",
        e.When, e.What)
}

func run() error {
    return &MyError{
        time.Now(),
        "it didn‘t work",
    }
}

func main() {
    if err := run(); err != nil {
        fmt.Println(err)
    }
}

 

A Tour of Go Errors

原文:http://www.cnblogs.com/ghgyj/p/4057736.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!