SoFunction
Updated on 2025-03-03

How to handle Go custom error errors

Go's error is more flexible. However, its own error processing mechanism is not very useful, so we can customize the error output:
As long as all objects that implement the Error() method are OK, here is a relatively simple demo, and an error optimization package is sorted out:

package main

import (
 "fmt"
)

type NameEmtpyError struct {
 name string
}
//NameEmtpyError implements the Error() method object.func (e *NameEmtpyError) Error() string {
 return "name cannot be empty"
}

func NameCheck(name string) (bool, error) {
 if name == "" {
  return false, &NameEmtpyError{name} // Note that error must be address & reference }
 return true, nil
}

func main() {
 name := ""
 if check, err := NameCheck(name); err != nil {
  (err)
 } else {
  (check)
 }

}

There are two ways to define error exceptions in go, but both of them require that your return value is of error type:
The first way is to use the golang standard library package errors to define the error. It is simple to use, just return ("Error Message"). This is the easiest error return.

The second way is to borrow the struct structure and create a struct Error() method. Note that the method name is Error, otherwise the Error method will not be found.
Let's take a look at a more complete method of using Error. Not only errors, but also struct Error() method.

package main

import (
 "errors"
 "fmt"
)

type equalError struct {
 Num int
}

//The method name is Error()func (e equalError) Error() string {
 return ("The current number is %d, greater than 10", )
}

//Use simple generationfunc Equal(n int) (int, error) {
 if n > 10 {
  return -1, ("Greater than 10") //Generate a simple error type }
 return n, nil
}

func DiyEqual(n int) (int, error) {
 if n > 10 {
  return -1, equalError{Num: n} // The Error method of equalError will be called }
 return n, nil
}

func main() {
 //Use error object if result, err := Equal(20); err != nil {
  ("mistake:", err)
 } else {
  ("result:", result)
 }

 //Not applicable to erros, custom error method. if result, err := DiyEqual(20); err != nil {
  ("mistake:", err)
 } else {
  ("result:", result)
 }

}

Of course, it is not recommended to write this in actual development projects. If you don’t say it too low, it is not easy to expand. In the next article, I will write a demo to encapsulate and optimize the error output.

This is the end of this article about Go custom error error. For more information about Go custom error error, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!