fmt.Printf("Type of myErr is %T \n", myErr)
fmt.Printf("Value of myErr is %v \n", myErr)
-------------------------------------------------------
Type of myErr is *errors.errorString
Value of myErr is &errors.errorString{s:"Something unexpected happend!"}
package main
import "fmt"
import "errors"
// divide two number
func Divide(a, int, b int) (int, error) {
// can not divide by '0'
if b == 0 {
return 0, errors.New("Can not device by Zero!")
} else {
return (a / b), nil
}
}
func main() {
//divide 4 by 0
if result, err := Divide(4, 0); err != nil {
fmt.Println("Error occured: ", err)
} else {
fmt.Println("4/0 is", result)
}
}
---------------------------------------------------------------------------------
Error occured: Can not devuce by Zero!
package main
import "fmt"
//network error
type NetworkError struct {}
func (e *NetworkError) Error() string{
return "A network connection was aborted"
}
// file save fail error
type FileSaveFailedError struct {}
func (e *FileSaveFailedError) Error() string{
return "The requested file could not be saved."
}
// a function that can return either of the above errors
func saveFileToRemote() error {
result := 2 //mock result of save operation
if result == 1 {
return &NewNetworkError()
} else if resutl == 2 {
return &FileSaveFailedError{}
} else {
return nul
}
}
func main() {
// check type
switch err := saveFileToRemote(); err.type {
case nil:
fmt.Println("File successfully saved.")
case *NetworkError:
fmt.Println("Network Error:", err)
case *FileSavedFailedError:
fmt.Println("File save Error:", err)
}
}
--------------------------------------------------------------------------
File save Error: The request file could not be saved.
package main
import "fmt"
//simple user unauthorized error
type UnauthorizedError struct {
UserId int
OriginalError error
}
// add some context to the original error message
func (httpErr *UnauthorizedError) Error() string {
return fmt.Sprintf("User unauthorized Error: %v", httpErr.OriginalError)
}
// mock function call to validate user, returns error
func validateUser{ userId int } error {
//mock general error from a function call: getSession(userId)
err := fmt.Errorf("Session invalid for user id %d", userId)
//return UnauthorizedError with original error
return &UnauthorizedError{userId, err}
}
func main() {
//validate user with id '1'
err := validateUser(1)
if err != nil {
fmt.Println(err)
} else {
fmt.Println("User is allowed to perform this action!")
}
}
--------------------------------------------------------------------
User unauthorized Error: Session invalid for user id 1