The goal of this tutorial is to teach you how to create and handle custom errors in Go. We'll cover creating your own error types and using them in your Go programs.
In Go, an error is a built-in interface that represents an abnormal state. The error
interface is very simple, it contains a single method, Error()
, which returns a string.
To create custom error types in Go, we create a new type that implements the error
interface. This is done by creating a struct for the error type and providing an Error()
method for the struct.
Custom errors are handled in the same way as standard errors. The error
returned by a function can be checked and handled appropriately.
type MyError struct {
Msg string
}
func (e *MyError) Error() string {
return e.Msg
}
In this snippet, we create a new error type called MyError
. It has a single field Msg
which is the error message. The Error()
method returns this message.
func someFunc() error {
// ... some code
return &MyError{"Something went wrong"}
}
In this function, we return an instance of MyError
when something goes wrong.
err := someFunc()
if err != nil {
fmt.Println(err)
}
Here, we check if someFunc()
returns an error. If it does, we print the error message.
In this tutorial, you learned how to create and handle custom errors in Go. You now know how to create your own error types and how to use them in your Go programs.
To further your understanding, consider reading more about error handling in Go and try to implement custom errors in your own projects.
Create a custom error type MathError
that has two fields: Op
for the operation and Msg
for the message. In the Error()
method, return a string that includes both the operation and the error message.
Write a function Divide(x, y int)
that returns an error if y
is zero. Use the MathError
type for the error.
type MathError struct {
Op string
Msg string
}
func (e *MathError) Error() string {
return fmt.Sprintf("%s: %s", e.Op, e.Msg)
}
func Divide(x, y int) (int, error) {
if y == 0 {
return 0, &MathError{"Divide", "Cannot divide by zero"}
}
return x / y, nil
}
Try to expand the Divide()
function to handle more math operations and use the MathError
type to return different error messages for different error situations.