The Go language has an in-built type error
that is used for error handling. error
simplifies identifying which function/s or code returns an error, and why the error has occurred. To use error
, you must first import the errors
package, as shown below:
import (
"errors"
)
An error
type can return as nil
or not. If it is nil
, then there is no error.
The following example will help you understand the error
type better. In the example below, the user is first asked to input their age into an online screening system for job applications. After acquiring their age, we use a program to check whether it’s invalid, underage, or valid. If their age is invalid or underage, the required error is returned to indicate so. If not, the error returned is nil
.
package mainimport ("fmt""errors")func check(age int)(string, error){if age < 0{ //code for invalide age of employeereturn "",errors.New("Invalid age")} else if age < 20{ //code for invalide age of employeereturn "",errors.New("Under age")} else { //if the age is above 20return "Can apply!", nil}}func main() {//take input from userfmt.Println("Enter Your Age: ")var age intfmt.Scanln(&age)validity, err := check(age)if err != nil {fmt.Println(err)} else {fmt.Println(validity)}}
Enter the input below
Apart from New()
, there are three more functions in the error
package:
Name | Prototype | Description |
---|---|---|
As() |
func As(err error, target interface{}) bool |
Looks for error in an error chain. Upon success, sets target to the error and returns true . |
Is() |
func Is(err, target error) bool |
If the target matches the error, then the function returns true . |
Unwrap() |
func Unwrap(err error) error |
Returns an error if the Unwrap() call to an error returns an error. Otherwise, it returns nil . |
Free Resources