0
0
Goprogramming~5 mins

Custom error types in Go

Choose your learning style9 modes available
Introduction

Custom error types help you give more details about problems in your program. They make it easier to understand and fix errors.

When you want to add extra information to an error, like a code or description.
When you need to check the type of error to handle it differently.
When you want to group related errors together with specific details.
Syntax
Go
type MyError struct {
    Message string
    Code    int
}

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

You create a struct to hold error details.

Implement the Error() string method to satisfy the error interface.

Examples
This error type shows when a resource is missing.
Go
type NotFoundError struct {
    Resource string
}

func (e NotFoundError) Error() string {
    return e.Resource + " not found"
}
This error type explains what field is invalid and why.
Go
type ValidationError struct {
    Field string
    Problem string
}

func (e ValidationError) Error() string {
    return fmt.Sprintf("Invalid %s: %s", e.Field, e.Problem)
}
Sample Program

This program defines a custom error type MyError. The function doSomething returns this error when a condition is false. In main, we check the error and print its message and code.

Go
package main

import (
    "errors"
    "fmt"
)

type MyError struct {
    Message string
    Code    int
}

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

func doSomething(flag bool) error {
    if !flag {
        return MyError{Message: "Something went wrong", Code: 123}
    }
    return nil
}

func main() {
    err := doSomething(false)
    if err != nil {
        fmt.Println(err)

        var myErr MyError
        if errors.As(err, &myErr) {
            fmt.Printf("Custom error code: %d\n", myErr.Code)
        }
    } else {
        fmt.Println("All good!")
    }
}
OutputSuccess
Important Notes

Always implement the Error() string method so your type works as an error.

Use errors.As to check and extract your custom error type safely.

Summary

Custom error types let you add details to errors.

Define a struct and implement Error() string method.

Use errors.As to detect and handle your custom errors.