Error Handling Tutorial with Golang


Introduction to Golang Error Handling

As you may already know, Golang has a different way of treating errors, there is no try/catch. You must explicitly check for errors right after calling a function. Like the following example:

Example 1 — https://go.dev/play/p/Ig6GeVKJtrG

In the code above, we called the function Println from the fmt package. It prints a message on the standard output and returns the number of bytes written as the 1st argument and any write errors encountered as the 2nd argument.

As in this example, we don’t care about the number of bytes written, we put an underline on the first argument, and as we want to handle the error, we create a variable named err on the second argument.

Then we just check if the error is not nil; if there is an error. If so, we panic the whole application with the error message.

Understanding Panic in Golang

When you call panic, it immediately calls all the defers defined in the function, which means that if we had a defer on the main function, it would be executed before the panic. See the example below:

Example 2 — https://go.dev/play/p/OdCuAXq3IPm

In the example above, if we had an error in printing the message, line 12 would be executed, panicing the whole application. But as mentioned before, panic calls all the defers defined before doing anything. So in this example, before panicing no line 12, line 8 would be executed.

FIYdefers run in the reverse order that you define, it means that the last written is the first executed.

Panicing a complex Golang application

Let’s imagine you have a robust system with many nested functions. What would happen if it would panic in the deepest function? I know it is hard to imagine, but take a look at the example below:

Example 3 — https://go.dev/play/p/SIsn_LY-9HS

In the example above, we have four functions, the first one calls the second one; the second one calls the third one; the third one calls the fourth one; the fourth one panics the whole application.