GOLANG

Error handling in Go

Go does not provide conventional try/catch method to handle the errors, instead, errors are returned as a normal return value. In this article, we are going to explore error handling in Go.

Uday Hiwarale
RunGo
Published in
13 min readJun 12, 2019

--

(source: pexels.com)

Conventionally, we learned an error is something that is fatal to the program but in Go, error has a different meaning. An error is just a value that a function can return if something unexpected happened.

So what could happen in a function that is unexpected? For example, the function was invoked with wrong arguments or execution inside the function did not go as expected. In that case, this function can return an error as a value.

error is a built-in type in Go and its zero value is nil. An idiomatic way to handle an error is to return it as the last return value of a function call and check for the nil condition.

val, err := myFunction( args... );if err != nil {
// handle error
} else {
// success
}

If you are familiar with the Node.js, then any async function callback returns an error as the first argument. In Go, we follow the same norm.

Let’s first understand what error looks like. As we know the error is a built-in type but in reality, it is an interface type made available globally and it implements Error method which returns a string error message.

type error interface {
Error() string
}

As we learned from interfaces lesson, the zero value of an interface is nil. Hence, any type that implements the error interface is as an error. So, let’s create our first error by implementing error interface.

https://play.golang.org/p/ciha7WtKbMt

From the above example, we have created a struct type MyError which implements Error method. This method returns a string. Hence, struct MyError implements the error interface. So in nutshell, myErr is an error now. Println function is designed to call Error method automatically when the value is an error hence error message something

--

--