Let's start with creating your custom error type. If you come from languages such as C# and Java, you may find the error mechanism a little different in Go. Moreover, the way you create your own custom error is very simple because Go is a duck-typed language, which means that you are good to go as long as your struct satisfies an interface. Let's go ahead and create our own custom error using a new type. So, I will have two fields, ShortMessage
and the DetailedMessage
of string type. You can have as many fields as you want, to capture more information about your errors. Furthermore, to satisfy the error
interface, I'm going to implement a new method, *MyError
, which will return a string
value, and we can output this error to either our console or some log file.
Then, what I'm going to do is to return the error message. So, the way you do this is very simple: you can just return this error type from your method. Let's imagine that we have a doSomething
method that...