golang

Custom Errors in Go (Custom Error)

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

In Go, like any other programming languages, errors provide mechanism for anticipating and handling the potential unexpected situations while providing helpful and meaningful feedback to the user.

Luckily, in Go, we have access to a plethora of tools and features for effective error handling. However, you may come across instances where the built-in error messages and features do not capture your actual app requirements.

This is where custom errors come into play. As the name suggest, custom errors allow us to define a precise and specific information for error messages that match the application.

In this tutorial, we will walk you through the process of setting up the custom errors in Go, explain why you might need them, and discover come examples along the way on how to work with custom errors.

Basics of Error Handling

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.

Golang Custom Errors

As the name suggests, custom errors are basically user-defined error types that implements the error interface. The role of custom errors is to allow us to create the error objects with custom fields and behaviors. This helps to provide more context and specificity in the error message to enhance the error handling.

Uses of Custom Errors

You may be wondering why you need the custom error types while you can use the basic logging techniques using the built-in features.

While the built-in error types are more than sufficient for a wide array of cases, there are several advantages to custom error types such as:

  1. Explicit Context – Custom errors provide an added layer of context about the error which makes it easier to understand and debug. Some added information about custom errors includes the function where the error occurred, any relevant data associated with it, and more.
  2. Type Safety – Since custom error are types themselves, they allow us to define the methods on them which allows us to create a structured and type-safe error handling logic.
  3. Encapsulation – Custom errors allow us to encapsulate specific domain rules which can lead to a cleaner code.

Create the Custom Error Types

To create the custom errors in Go, we basically need to define our own custom error types that implement the error interface.

The following shows a basic structure of defining a custom error in Go:

type CustomError struct {
    Msg string
    Code int
}
func (e *CustomError) Error() string {
    return e.Msg
}

 

In the given example code, we define a custom error type called “CustomError” with the fields for the “Msg” message and the “Code” error code as an integer.

We then implement the Error() method on the “CustomError” which returns the error message.

Finally, we can create a custom error using this error type as shown in the following example:

func func() error {
  return &CustomError{Msg: "Something went wrong", Code: 42}
}

 

Use the Custom Errors in Go

Once we create the custom errors, we can use them in the code just like any other built-in error.

The following example shows how to use the “CustomError” that we defined in the previous step:

func main() {
    err := func()
    if err != nil {
        if err, ok := err.(*CustomError); ok {
            fmt.Printf("Custom Error: %s (Code: %d)\n", err.Msg, err.Code)
        } else {
            fmt.Println("Generic error:", err)
        }
    } else {
        fmt.Println("No error occurred.")
    }
}

 

In the given example, we call a function called “func” and check if it returns an error. If it does, we use the Golang type assertion to check if it’s of “CustomError” type. If it is true, we access the “Msg” and “Code” custom fields.

Conclusion

In this tutorial, we taught you everything you need to know about custom errors in Go. We learned about the error interface, the Error() method, how to implement it, how to create the custom error types, and how to use the custom error types.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list