Home > Backend Development > Golang > How Golang defines error

How Golang defines error

angryTom
Release: 2020-03-14 16:36:47
Original
3350 people have browsed it

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
}
Copy after login

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
}
Copy after login

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)
}
Copy after login

3. Run the test

go run ./test.go
Copy after login

PHP Chinese website , a large number of programming tutorials and website 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template