Ad space (banner)
๐ŸนGo Lessons
Lesson 25 / 68

Writing a Custom Error Type

In this lesson you will learn how to define your own error type in Go so you can describe error conditions more precisely. This is for anyone searching for "Go custom error how to create".

Creating a struct that satisfies the error interface gives you an error of your own. Giving each kind of failure its own type makes it easy to tell what went wrong using errors.As().

The sample code has the ValidationError struct satisfy the error interface by implementing an Error() string method, and returns it from checkAge() when the age is negative. The caller then tests for that specific kind with errors.As(err, &ve).

A common stumbling block for beginners is sticking with plain errors.New() and losing the ability to tell error types apart. Once you can distinguish "invalid input" from "network failure", you can write a response suited to each.

In real-world development, the larger the application, the more this kind of error-type design matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)