Home>Article>Backend Development> How Golang defines error

How Golang defines error

angryTom
angryTom Original
2020-03-14 16:36:47 3226browse

How Golang defines error

How Golang defines error

During the development process, when the error content returned by the standard library could no longer meet our needs, we found builtin. error in go is an interface,

Related recommendations:golang tutorial

type error interface { Error() string }

So you only need to create a structure containing the Error() string function.

1. Create a new errors package under go path

vim $GOPATH/github.com/mypractise/error/errors.go

package errors type Error struct { ErrCode int ErrMsg string } func NewError(code int, msg string) *Error { return &Error{ErrCode: code, ErrMsg: msg} } func (err *Error) Error() string { return err.ErrMsg }

2. Start calling the errors package

vim ./test.go

package main import ( "encoding/json" "errors" "fmt" myerr "github.com/mypractise/errors" ) func myErr() error { err := myerr.NewError(2, "err test") return err } func staErr() error { m := make(map[string]string) err := json.Unmarshal([]byte(""), m) if err != nil { return err } return errors.New("aaaaa") } func main() { err1 := staErr() fmt.Println("------sta err:", err1.Error()) err2 := myErr() fmt.Println("------my err:", err2.Error(), err2.(*myerr.Error).ErrCode) }

3. Run the test

go run ./test.go

PHP Chinese website , a large number of programming tutorials andwebsite construction tutorials, welcome to learn.

The above is the detailed content of How Golang defines error. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn