How to Create Custom Error Types in Go

Create a custom error type in Go by defining a struct with an Error() method to return a descriptive string.

Define a custom error type by creating a struct that implements the error interface with an Error() string method. This allows you to attach specific context or data to the error, which you can then check using errors.Is or errors.As.

package main

import (
	"errors"
	"fmt"
)

type MyError struct {
	Code int
	Msg  string
}

func (e *MyError) Error() string {
	return fmt.Sprintf("error %d: %s", e.Code, e.Msg)
}

func main() {
	err := &MyError{Code: 404, Msg: "not found"}
	if errors.Is(err, &MyError{}) {
		fmt.Println("Handled")
	}
	fmt.Println(err)
}