Ir - Manejo de errores

La programación Go proporciona un marco de manejo de errores bastante simple con el tipo de interfaz de error incorporado de la siguiente declaración:

type error interface {
   Error() string
}

Las funciones normalmente devuelven error como último valor devuelto. Utilizarerrors.New para construir un mensaje de error básico de la siguiente manera:

func Sqrt(value float64)(float64, error) {
   if(value < 0){
      return 0, errors.New("Math: negative number passed to Sqrt")
   }
   return math.Sqrt(value), nil
}

Utilice el valor de retorno y el mensaje de error.

result, err:= Sqrt(-1)

if err != nil {
   fmt.Println(err)
}

Ejemplo

package main

import "errors"
import "fmt"
import "math"

func Sqrt(value float64)(float64, error) {
   if(value < 0){
      return 0, errors.New("Math: negative number passed to Sqrt")
   }
   return math.Sqrt(value), nil
}
func main() {
   result, err:= Sqrt(-1)

   if err != nil {
      fmt.Println(err)
   } else {
      fmt.Println(result)
   }
   
   result, err = Sqrt(9)

   if err != nil {
      fmt.Println(err)
   } else {
      fmt.Println(result)
   }
}

Cuando el código anterior se compila y ejecuta, produce el siguiente resultado:

Math: negative number passed to Sqrt
3