SoFunction
Updated on 2025-03-05

Detailed explanation of how to return a custom error type in Golang

Previous article "Detailed explanation of errors package in Golang》 explains in detail the main types and functions of the errors package, as well as their usage methods. This article combines the knowledge explained before to explain how to return a custom error type according to your own or your team's project requirements.

Why custom error type is required

In daily development, returning a custom error type is a common practice, because in many scenarios, the error type in the standard library errors package cannot meet the needs. For example, when developing a web project, the common return structure may be as follows:

{"code":xxx, "data":yyy,"msg":"zzz"}

code is the status code, data is the service data returned by the interface, and msg is the error message. For this response structure, it is generally practiced to call functions or methods that process business logic, return business data and errors, and then assemble this structure at the API layer. Therefore, the error object must at least contain status code code and error message msg, and you need to implement your own error type.

How to implement custom error types

In Golang, you can return a custom error type by creating a structure that implements an error interface (which only contains an Error method). Custom error types can contain fields and methods that you define yourself to provide more error information and context information. See an example to show how to create and return a custom error type:

package main
import (
    "errors"
    "fmt"
)
// Custom error typetype MyError struct {
    code int64
    msg  string
}
// Error method to implement error interfacefunc (e MyError) Error() string {
    return ("Error: [%d] %s", , )
}
func (e MyError) Code() int64 {
    return 
}
func (e MyError) Msg() string {
    return 
}
// Function example, return a custom error typefunc doSomething() error {
    err := MyError{
        code: 500,
        msg:  "Something went wrong",
    }
    return err
}
func main() {
    err := doSomething()
    if err != nil {
        (err)
    }
    // Compare custom error types    myErr := MyError{
        code: 500,
        msg:  "Something went wrong",
    }
    equal := (err, myErr)
    (equal) // true
}

In the above example, a custom MyError type is first defined, including two fields code and msg, and then the Error method required by the error interface is implemented.

Next, let’s take a look at a specific usage example combining the gin framework. The simple example code is as follows:

package main
import (
    "errors"
    "fmt"
    "/gin-gonic/gin"
    "net/http"
)
// Custom error typetype MyError struct {
    code int64
    msg  string
}
func NewError(code int64, msg string) MyError {
    return MyError{
        code: code,
        msg:  msg,
    }
}
// Error method to implement error interfacefunc (e MyError) Error() string {
    return ("Error: [%d] %s", , )
}
func (e MyError) GetCode() int64 {
    return 
}
func (e MyError) GetMsg() string {
    return 
}
// Function example, return a custom error typefunc doSomething() error {
    err := MyError{
        code: 500,
        msg:  "Something went wrong",
    }
    return err
}
func FromError(err error) MyError {
    if err == nil {
        return NewError(1, "")
    }
    if !(err, &MyError{}) {
        return NewError(-1, "")
    }
    return err.(MyError)
}
func TestHandler(c *) {
    err := Logic()
    if err != nil {
        e := FromError(err)
        (, {"code": (), "data": nil, "msg": ()})
        return
    }
    (, {"code": 1, "data": nil, "msg": ""})
}
func Logic() error {
    return NewError(-1, "something went wrong")
}
func main() {
    r := ()
    ("/test", TestHandler)
    (":8080")
}

summary

By returning a custom error type, you can provide more error information and context information, making error handling more flexible and accurate. You can create custom error types based on your actual needs and application scenarios.

This is the article about how to return a custom error type in Golang. For more related go errors content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!