[Golang] Error in Golang

Tags
Golang
Engineering
Created
Nov 7, 2023 04:54 AM
Edited
Nov 6, 2023
Description
error handling and custom error

Error (no exception)

// return multiple results
import (
	"fmt"
	"errors"
	"math"
)

func sqrt (x float64) (float64, error) {
	if x < 0 {
		return 0, errors.New("Undefined for negative numbers")
	}
	
	return math.Sqrt(x), nil
}

func main() {
	result, err := sqrt(16)

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

Custom Error

As with fmt.Stringer, the fmt package looks for the error interface when printing values.
package main

import (
	"fmt"
	"time"
)

type MyError struct {
	When time.Time
	What string
}

func (e *MyError) Error() string {
	return fmt.Sprintf("at %v, %s",
		e.When, e.What)
}

func run() error {
	return &MyError{
		time.Now(),
		"it didn't work",
	}
}

func main() {
	if err := run(); err != nil {
		fmt.Println(err)
	}
}

Source