Golang custom error

Time:2020-2-27

The error processing of the system itself is generally errors. New() or FMT. Errorf(), etc., which is not very friendly to those that need complex display. We can extend the error.

Error is defined as an interface type in the standard library, which has only one error () method

type error interface {
  Error() string
}

So, as long as the user-defined error has the error () method, it implements the error interface. Here we use the structure to extend

package errors

import (
    "encoding/json"
)

type Err struct {
    Code int
    Msg   string
}

func (e *Err) Error() string {
    err, _ := json.Marshal(e)
    return string(err)
}

func New(code int, msg string) *Err {
    return &Err{
        Code: code,
        Msg:   msg,
    }
}

call

func main(){
    Fmt.println (errors.new (401, "no permission")
}

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]