Go Errors

Topics Covered

Overview

Golang is an open-source, procedural, and statically typed programming language. It provides a rich standard library, garbage collection, and dynamic-typing capability.

Golang error is the most crucial inbuilt package used to display a message to highlight an error in the code.

Introduction

An error is an unexpected output a program returns. It can be addressed in several ways by displaying a message using the method errors.New() or by displaying the message along with the specifier to print a value by using the method Errorf().

Golang Error Handling

Golang errors in the program can be handled by using an inbuilt package errors which is to be imported into the starting lines of the program, it helps in displaying the message when an error is encountered. There are two types of functions new() and errorf().

New() Function

To use this function we first need to import the errors package then we use this function to display a message whenever an error is encountered.

In the above code, we are checking whether the message in the main function is matching with the one we have created in the validate function. Inside the validate function, we create an error and check if the message that is passed in the function is not equal to the message "Hello World" then we return the error otherwise if it is equal then we return nil. Now in the main function, we see the message is "Hi". It is passed in the function validate and the result is stored in e. We check if e is not equal to nil then we print the result stored in e that is the error because the message "Hi" is not equal to "Hello World" but if e was nil then we would have printed "Valid Message".

Errorf() Function

The following function is used to create a formatted error. In other words, we can say that this function in golang error enables us to create a message that includes the value also using an identifier. For using errorf we need not import the package error.

In the above code, we first assigned a value to the year which is -2004. We created an error using Errorf in which we are printing a statement that contains the value assigned to the year. Next, we checked if the value stored in the year is less than 0 or not, if it is less than zero then we print the error else we print the year.

Custom Errors in Golang

We can create a custom error for the code by constructing a struct with an error interface.

  • At first, we create a struct named operationbyzero within which an error message is in the form of a string.
  • We create a function for the error in which we implement an error method in the struct operationbyzero.
  • We also create a function named divide for dividing a number in which we take two integer parameters and an error. * Next we check whether the number at the denominator is 0 or not, if it is 0 then we return zero and the operationbyzero struct. Otherwise, if the denominator is not zero then we return the result of the division and nil.
  • In the main function, we store the return of the function divide in the variable result and e, we check whether the returned function in the result is nil or not. If it is not nil then we print the returned value of the function divide, otherwise, we print the result of the operation.

Error Methods

a. Func As

As searches over err chain until it finds the first error that matches the target; if it does, it sets the target to that error value and returns true. Otherwise, false is returned.

The output of the above code is

In the above code, we first import the error and initialize badinput as "def", in the function validateInput, we check whether the input is badinput or not if it is then we print the badinput. In the main function, we call the validateInput function and store the return value in e and use the error.As() with parameters (e, &badInputErr), if this function is true then we print badInputErr.

b. Func Is

A built-in function of the Unicode package called Is() is used to determine whether a particular rune is part of a given table of ranges. Rune is a data type. Each int value is translated into a Unicode code via the character literal "rune", which represents an int32 value.

The function takes two parameters (RangeTable, rune) and returns true if the rune is a member of the range table, it returns false if the rune is not a member of the range table, that is, it returns the value in bool type.

The output of the above code is

In the above code, we check whether the rune "A" is in the range table of Latin or not, for which a bool-type result is generated when we call the unicode.Is() function. Similarly for white spaces also check for "\t" for which a true value is returned since the tab creates a space. On the contrary, for "/b" we get a false result since it does not give a white space.

c. Func new

A built-in function called new() is used to allocate memory. The first argument is not a value rather it is a type, and the returned value is a pointer to a newly allocated zero value of that type.

The output of the above code,

In the above code, we created a string s1 and s2, and we sliced the string s2 to [0:10]. Upon printing the type of both of the strings we see that string s1 is of pointer type since it is returned by the new() function, whereas the string s2 is not of pointer type because it has been sliced from 0 to 10.

d. Func Unwrap

If the type of err contains an Unwrap method returning the error, Unwrap returns the outcome of calling the Unwrap method on err. If not, Unwrap returns zero.

The output of the above code is

In the above code, we first import the error, then in the main method, we call the error which contains another error. Therefore on unwrapping, we see the error contained inside it.

Conclusion

Hello developer! I am sure by now you must have understood what golang errors are. Let us summarize what we have learned so far

  • Golang is an open-source programming language that is procedural and statically typed. It provides a rich standard library, garbage collection, and dynamic-typing capability.
  • Golang errors are the most crucial inbuilt package used to display a message when we want to highlight an error in our piece of code.
  • An error is an unexpected output a program returns.
  • Golang errors in the program can be handled by using an inbuilt package errors which is to be imported into the starting lines of the program, it helps in displaying the message when an error is encountered.
  • As() searches over err chain until it finds the first error that matches the target; if it does, it sets the target to that error value and returns true. Otherwise, false is returned.
  • A built-in function of the Unicode package called Is() is used to determine whether a particular rune is part of a given table of ranges.
  • A built-in function called new() is used to allocate memory. The first argument is not a value rather it is a type, and the returned value is a pointer to a newly allocated zero value of that type.
  • If the type of err contains an Unwrap method returning an error, Unwrap returns the outcome of calling the Unwrap method on err. If not, Unwrap returns zero.