You’ll love Golang’s approach to error handling

You'll love Golang's approach to error handling

One of the marks of a great app is good error handling. Ever since I started my programming career, this is something I have always grappled with. For instance you build a login or registration form, but then the user enters values that the app doesn’t expect….say the app expects phone numbers in international format like so 256787123456, but the user enters the normal format 787123456. Without validation and error handling, your app will simply crash without you or the user knowing why.

I have Java, Python, Ruby and PHP background and how they handle errors is via raising exceptions and then handling them via try and catch blocks. Let me write some pseudo python code to illustrate how this works.

class ValidationError(Exception):

except ValidationError as e:
  print("wrong phone format entered, %s" % e)

def validate_phone(phone_no):
	if is not correct_phone_format():
		raise ValidationError("wrong phone number entered")

So if validation fails, we raise an exception and then we catch it when we call the validation function.

But Go doesn’t like this approach that much. Instead Go believes in returning errors each time something fails, or no error if everything goes well. The caller then has to check if there’s an error using if statements. If none, then we grab the returned value and move on. This is how it’s done in Go. Let’s write some pseudo code illustrate the same thing in Go.

phone, err := validate_phone(some_phone_no)
if err != nil{
	fmt.Println("wrong number entered: %s", err)
// otherwise  phone is correct, proceed

func validate_phone(phone_no) (phoneNo, error) {
	if correct_phone_format() {
		return correct_phone_no, nil
	} else {
		return nil, errors.New("wrong phone number entered")

See, we don’t have any try and catch blocks here, but we achieve the same results in my opinion quite simply. If you call the validate_phone function without assigning two variables, the compiler will immediately complain forcing the programmer to always handle errors whether they like it or not. In the previous case of python, I might still get away with calling the function without necessarily handling the exception which is a big problem if an error occurs.

First timer Gophers will frantically wonder why Go doesn’t have try/catch blocks. But once you know the Go approach to error handling, you’ll love it. Currently I am doing my side project, Site Monki, a monitoring tool ( which is build using both Python on the front-end and Go as the backend and I am absolutely loving the experience.


Leave a Reply