The fmt package also provides you with an errorf function to generate custom and descriptive error messages. The function supports custom formatting specifiers and creates informative error messages for users and developers.
Let us learn how we can create custom error messages using the fmt.Errorf Function.
Function Syntax
The function definition is as shown:
The function accepts two parameters:
- The format as a string containing the custom specifiers used by the function to format the actual error message.
- The interface contains a list of arguments to replace the custom specifier values in the error message string. You can pass any number of arguments of any time provided the specifier is set.
Format Specifiers
The following are some common specifiers to use with the errorf function:
- %s – Print a string.
- %d – print an integer
- %f – floating point number.
- %v – print values of a struct.
- %+v – print struct fields and values.
- %t – print Boolean.
- %b – print binary value.
- %e – scientific notation
These common specifiers are used with the errorf function. Check the following documentation provided to learn more.
The function should return the error message generated according to the format specifier and the passed arguments.
Example 1
The following code shows how to use the errorf function to generate a custom error message:
import"fmt"
funcmain() {
const username, uid = "debian", 1000
err := fmt.Errorf("[Error!]...Username %s of uid: %d not found.", username, uid)
fmt.Println(err)
}
In the previous code, we create two constant variables holding a string and an int. We then use the Errorf method to generate a custom error message with the %s and %d formatters for a string and integer, respectively.
The code above should return an error message as:
Example 2
We can also format a struct using the %v or %+v specifiers. An example is provided below:
import"fmt"
type user struct {
first_name, last_namestring
}
funcmain() {
user1 := user{"Jane", "Doe"}
err := fmt.Errorf("Struct info %+v", user1)
fmt
The previous code should print the struct field and values as shown below:
Example 3
We can also include the timestamp for an error message using the built-in time methods. An example is provided below:
import (
"fmt"
"time"
)
funcmain()
err := fmt.Errorf("An error occurred at: %v", time.Now().Format("2006-01-02T15:04:05Z07:00"))
fmt.Println(err)
}
The previous code should include the current time formatted according to RFC3339 formatting options.
The resulting output is as shown:
Conclusion
This guide covered the fundamentals of generating custom error messages using the fmt.Errorf function, plus several examples for review. We hope you found this article helpful. Check out the other Linux Hint articles for more tips and tutorials.