Error Handling Code in Go

When you are coding any Go program, it is common to come across the error type. As of good coding practice, we should handle this abnormality from time to time, at least terminating the program with log.Fatal(err). After coding Go for more than 3 months, it is interesting to find that the error handling code contributes around 30~50% of the overall of the program. Does it mean the program will have less vulnerabilities? I think it really helps as the syntax of Go language always forces the programmer to focus on handling the abnormality. Below are some tips for error handling in GO after coding for a while.
  • Never ignore the error type returned from any function. Go allows you to ignore it with _, but please don't do it.
  • When you define a new func, please design your function prototype with at least error type return even though your newly defined function is not going to return anything. This can facilitate by returning any error type from another function to the callee, eventually the error type is bubbling up back to the main func and can be handled over there.
  • It is not recommended to terminate the program when we get the error type within a function, as it is not testing friendly when you are coding the unit test case of your newly defined function.
  • When we encounter the error type in the main func, we should at least terminate the program with log.Fatal(err). 
Thanks for the feature of GO allowing function to have multiple return values. :)


Reference:

Comments