GO language standard error handling mechanism error usage example

  • 2020-05-07 19:53:37
  • OfStack

This article illustrates the use of error, the standard error handling mechanism for GO. Share with you for your reference. Specific analysis is as follows:

In Golang, the error handling mechanism 1 is generally used when the function returns, which is the external interface, while the exception handling mechanism panic-recover 1 is generally used inside the function.

error type introduction

The error type actually abstracts the error interface of the Error() method, which Golang USES for standard error handling.

type error interface {
 Error() string
}

In general, if the function needs to return an error, error is the last of several return values (but this is not mandatory). Reference model:
func Foo(param int) (n int, err error) {
 // ...
} if n, err := Foo(0); err != nil {
        // Error handling
}

This is how to use error, which is easier and more intuitive than exceptions in other languages.

code 1: classic usage

package main
import (
 "errors"
 "fmt"
) func requireDual(n int) (int, error) {
 if n&1 == 1 {
  return -1, errors.New(" You did not enter an even number ") // generate 1 A simple error type
 }  return n, nil
} func main() {
 if result, err := requireDual(101); err != nil {
  fmt.Println(" Error: ", err)
 } else {
  fmt.Println(" Results: ", result)
 }
}

Output results:

Error: you did not enter an even number

Do you think the error handling mechanism of Golang is very simple?

code 2: expand the above code to error output with custom parameters

package main
import (
 "fmt"
) type dualError struct {
 Num     int
 problem string
} func (e dualError) Error() string {
 return fmt.Sprintf(" The parameter is incorrect because \"%d\" Not the number ", e.Num)
} func requireDual(n int) (int, error) {
 if n&1 == 1 {
  return -1, dualError{Num: n}
 }  return n, nil
} func main() {
 if result, err := requireDual(101); err != nil {
  fmt.Println(" Error: ", err)
 } else {
  fmt.Println(" Results: ", result)
 }
}

The output

Error: incorrect parameter because "101" is not an even number

I hope this article has helped you with your GO programming.


Related articles: