Go error

スポンサーリンク

error

There are a lot of situation to use error in go.

some methods return not only values but also error at the same time.

As error handling, check return error is nil or not.

error is defined like this

type error interface {
	Error() string
}

How to create error

There are 3 typical ways to do it.

  • New
  • fmt.Errorf
  • Extension

Let’s check in sample

errorsample.go

package basic2

import (
	"errors"
	"fmt"
)

func ErrorSample() {
	err1 := errors.New("Create new error")

	err2 := fmt.Errorf("Create new format error %d", 1)

	fmt.Println(err1)
	fmt.Println(err2)

	err3 := &NewError{Code: 3}
	fmt.Println(err3)
}

type NewError struct {
	Code int
}

func (e *NewError) Error() string {
	return fmt.Sprintf("New Error %d", e.Code)
}

Ref

3 simple ways to create an error

golang
スポンサーリンク
Professional Programmer2

コメント