Go語言錯誤處理小例子

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

         滿屏的error處理會是個悲劇,也不利於對錯誤進行區分處理。
建議在項目中多用自訂錯誤,再對錯誤集中處理。

package main//error處理方式示範//author: Xiong Chuan Liang//date: 2015-2-26import "fmt"import "errors"func main() {errType(test0())errType(test1(" test1 "))errType(test2(500))errType(test3(" test3 "))errType(test4(" test4 "))}type Error1 struct {arg    interrMsg string}func (e *Error1) Error() string {return fmt.Sprintf("%s", e.errMsg)}type Error2 struct {arg    stringerrMsg string}func (e *Error2) Error() string {return fmt.Sprintf("%s", e.errMsg)}func test0() error {return errors.New("errors.New() - test0()")}func test1(arg string) error {return fmt.Errorf("fmt.Errorf() - test1()")}func test2(arg int) *Error1 {return &Error1{arg, "Error1{} - test2()"}}func test3(arg string) error {return &Error2{arg, "Error2{} - test3()"}}func test4(arg string) *Error2 {return &Error2{arg, "Error2{} - test4() "}}func errType(err interface{}) {switch e := err.(type) {case *Error1:fmt.Println("Type:Error1 ", e)case *Error2:fmt.Println("Type:Error2 ", e)case error:fmt.Println("Type:error ", e)default:fmt.Println("Type:default ", e)}}/*運行效果:Type:error  errors.New() - test0()Type:error  fmt.Errorf() - test1()Type:Error1  Error1{} - test2()Type:Error2  Error2{} - test3()Type:Error2  Error2{} - test4()*/



MAIL: xcl_168@aliyun.com

BLOG: http://blog.csdn.net/xcl168


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.