How to create custom error messages in Go?

To create custom error messages in Go, you can create your own custom error type that implements the error interface. Here's an example:

package main import ( "fmt" ) // CustomError is a custom error type type CustomError struct { errMsg string } // Error returns the error message func (e *CustomError) Error() string { return e.errMsg } // NewCustomError creates a new instance of CustomError with the given error message func NewCustomError(msg string) error { return &CustomError{ errMsg: msg, } } func main() { // Raise a custom error err := NewCustomError("This is a custom error message.") fmt.Println(err.Error()) // Check the error type if _, ok := err.(*CustomError); ok { fmt.Println("CustomError type detected.") } }

In this example, CustomError is a custom error type that has an errMsg field. The Error method implements the error interface and returns the error message. The NewCustomError function creates a new instance of CustomError with the given error message.

You can then raise a custom error by calling NewCustomError with the desired error message. To check the error type, you can use a type assertion (_, ok := err.(*CustomError)) to check if the error is of type CustomError.

When executing the code, it will output:

This is a custom error message. CustomError type detected.

Note that this approach allows you to create more complex error types with additional fields or methods for more detailed error handling.