Error handling in Go language

    An error refers to an abnormal situation in the program, which causes the program to fail to execute normally.

Overview of error handling

  • There is no try...catch in Go
  • Go language provides a very simple error handling mechanism through built-in error types;
  • The error value can be stored in a variable and returned by a function;
  • If a function or method returns an error, by convention, it must be the last value returned by the function;
  • The idiomatic way of handling errors is to compare the returned error with nil;
  • A nil value means no error occurred, and a non-nil value means an error occurred;
  • If it is not nil, print out the error.

The nature of error

  • Error is essentially an interface type, which contains an Error() method.
    type error interface { Error() string }

  • Any type that implements this interface can be used as an error. This method provides a description of Go error handling-error.

How to create an error object

1. The New() function under the errors package returns an error object

  • Create a new error via errors.New().
package errors
// New returns an error that formats as the given text.
func New(text string) error {
   return &errorString{text}
}
// errorString is a trivial implementation of error.
type errorString struct {
   s string
}
func (e *errorString) Error() string {
   return e.s
}

2. The Errorf() function under the fmt package returns an error object

  • The Errorf() function under the fmt package essentially calls errors.New()
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, a ...interface{}) error {
	return errors.New(Sprintf(format, a...))
}

3. Create a custom error

The implementation steps are as follows:

  • 1. Define a structure to indicate the type of self-defined error;
  • 2. The method to make the custom error type realize the error interface: Error() string
  • 3. Define a function that returns error. It depends on the actual function of the program.

The case is as follows:
//myError.go



The effect is as follows:

Figure (1) Customized error handling mechanism

Guess you like

Origin blog.csdn.net/sanqima/article/details/108908579