go error接口与errors包详解

package main

import (
	"errors"
	"fmt"
)

type MsgError struct {
	Code int
	Msg  string
}
func (msg *MsgError) Error() string {
	return fmt.Sprintf("%s", msg.Msg)
}

func f1(code int) (int, error) {
	if code == 1 {
		return -1, errors.New("msg test error")
	}
	return code, nil
}


func f2(code int) (int, error) {
	if code == 1 {
		return -1, &MsgError{code, "struct msg test error"}
	}
	return code, nil
}

func main() {
	for _, v := range []int{1, 2, 3, 4, 5, 6} {
	      if code, err := f1(v); err != nil {
			fmt.Println(err)
		} else {
			fmt.Println("success:", code)
		}
	}
	for _, i := range []int{1, 2, 3} {
		if code, err := f2(i); err != nil {
			fmt.Println(err)
		} else {
			fmt.Println("success:", code)
		}
	}
}

转载地址:https://blog.csdn.net/xixihahalelehehe/article/details/105288886?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-1&spm=1001.2101.3001.4242

上一篇:Redis 高负载下的中断优化


下一篇:python爬虫学习视频资料免费送,用起来非常666