| by Arround The Web | No comments

Error Printing in Go (Print Error)

While error messages might not be the most enticing or the most motivating thing to see in development, they do play a crucial role in helping to determine the next course of action and, more importantly, prevent the programs from premature termination.

In this tutorial, we will walk you through the process of printing the error messages in Go.

Using Error.New()

Before we get into the woods of learning how to create and use the custom errors in Go, let us understand the basics of error handling in Golang.

Go presents errors using the error interface. The error interface has a single method called Error() string. Any type that implements this method allows Go to treat it as error.

Here, take a look at the following example code:

package main
import (
    "errors"
    "fmt"
)

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}
func main() {
    result, err := divide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Result:", result)
}

 

In the given example, we use the errors.New() function which allows us to create a new error with a descriptive message when we attempt to divide by zero.

Working with Multiple Errors

In a complex situation, an app may encounter multiple errors that are tied. A common technique is aggregating the errors and return them as a single unit.

In Go, we can accomplish this using the fmt.Errorf() function as shown in the following example:

package main

import (
    "fmt"
)

func operation1() error {
    return fmt.Errorf("err in op 1")
}

func operation2() error {
    return fmt.Errorf("err in op 2")
}

func main() {
    err1 := operation1()
    err2 := operation2()

    if err1 != nil || err2 != nil {
        err := fmt.Errorf("multiple errs:\n- %v\n- %v", err1, err2)
        fmt.Println("err:", err)
        return
    }
    fmt.Println("No errs.")
}

 

In this example, we are using the basic function operations to simulate the tasks that may return the errors. We then use the fmt.Errorf() function to combine them into single error messages.

Check our tutorial in Go error wrapping to learn more about how to add a context information to error messages.

Conclusion

In this tutorial, we learned how to work with error printing in Go using the new function and the “Errorf” function to combine multiple errors.

Share Button

Source: linuxhint.com

Leave a Reply