Creating Your Own Custom Errors

· 159 words · 1 minute read

In Go, although errors are a controversial subject, they are in fact very simple. As programmers of Go we also spend a lot of our time writing if err != nil. But we often also need to create these errors and pass them back to other functions to handle.

The errors package allows to create errors, as per the error interface, which can be dealt with like any other error. In our example below we handle the error on main() and produce the error in DoSomething().

package main

import (

func main() {
    // Run our function & catch any errors, we're going to report this error and exit.
    if err := DoSomeThing(); err != nil {

// DoSomething returns a type of error, these can be passed back directly from
// other functions inside this one, or created within it.
func DoSomeThing() error {
    return errors.New("Example Error, DoSomething has gone wrong!")
Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!