51. Go - Error Handling

Error Handling is used with functions that returns an err.

Uses second variable comma declarations.


Example:

print, err := fmt.Println("HELLO")
    if err != nil {
        fmt.Println("ERROR")
    }


Ways to Print Errors:

    fmt.Println(wgs, "FINISHED")
    print, err := fmt.Println("HELLO")
    if err != nil {
        fmt.Println("ERROR")
        log.Println("ERROR")
        log.Fatal()
        log.Fatalf("ERROR")
        log.Fatalln("ERROR")
        log.Panic()
        log.Panicf("ERROR")
        log.Panicln("ERROR")
    }

// Fatal exists program..

// Panic is mid serious, does not exit program and have ability to recover.

// Log gives ability to log the error into a file.

// fmt.print, prints error to standard output.


Logging

// prints or outputs into a designated file.

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    f, err := os.Create("logFile.txt")
    if err != nil {
        fmt.Println(err)
    }
    defer f.Close()

    log.SetOutput(f) // sets log default output to a text file.

    v, err := fmt.Println("HELLO")
    if err != nil {
        log.Println("ERROR") // prints and outputs into logFile.txt.
    }
}


Creating Custom Error Messages for Functions:

// using errors package

// returning an error type


Example:

package main

import (
    "errors"
    "fmt"
)

func main() {
    x, err := isZero(10)
    if err != nil {
        fmt.Println("ERROR:", err)
    }
    fmt.Println(x, err)
}

func isZero(x int) (bool, error) {
    if x == 0 {
        return true, nil
    } else {
        return false, errors.New("NOT A ZERO")
    }
}

// errors.New(STRING) returns an error type that has a string.


Example:

// using fmt.Errorf to format the message. returns a formatted errors.New

package main

import (
    "fmt"
)

func main() {
    x, err := isZero(10)
    if err != nil {
        fmt.Println("ERROR:", err)
    }
    fmt.Println(x, err)
}

func isZero(x int) (bool, error) {
    if x == 0 {
        return true, nil
    } else {
        return false, fmt.Errorf("%d is not a ZERO", x)
    }
}


Adding error type to structs:

// a struct with method Error() string {} implements the built in error interface.

// so struct will be a type error

// having custom struct error allows adding more info to errors message


Example:

package main

import (
    "fmt"
)

type Human struct {
    height int
    weight int
}

type createHumanError struct {
    height int
    weight int
    err    error
}

func (c createHumanError) Error() string {
    return fmt.Sprintf("AN ERROR OCCURRED WHEN CREATING HUMAN: %d height, %d weight, %v", c.height, c.weight, c.err)
}

func main() {

    x, err := createHuman(20, 400)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(x)
}

func createHuman(x, y int) (Human, error) {
    if x < 10 && y < 300 {
        return Human{
            height: x,
            weight: y,
        }, nil
    } else {
        err := fmt.Errorf("HUMAN VARIABLES TOO HIGH.")
        return Human{}, createHumanError{x, y, err}
    }
}


Example 2:

// using assertion to access the name variable in dogError.

// cant do e.name because name is not part of Error but part of dogError.

// use parenthesis to access dogError variables.


package main

import "fmt"

type dogError struct {
    name string
}

func (d dogError) Error() string {
    return fmt.Sprintf("ERROR: %v", d.name)
}

func main() {
    newErrors := dogError{
        "dogs",
    }

    x, y := takeError(newErrors)

    fmt.Println(x, y)
}

func takeError(e error) (string, string) {
    return e.Error(), e.(dogError).name
}



Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort