0
0
GoHow-ToBeginner · 3 min read

How to Use fmt.Errorf in Go: Simple Error Formatting

Use fmt.Errorf in Go to create an error with a formatted message by passing a format string and arguments, similar to fmt.Sprintf. It returns an error type that you can return or handle in your code.
📐

Syntax

The syntax of fmt.Errorf is similar to fmt.Sprintf. You provide a format string followed by any number of arguments to insert into the format.

  • format string: A string with verbs like %s, %d to format values.
  • arguments: Values to replace the verbs in the format string.
  • Returns an error with the formatted message.
go
err := fmt.Errorf("error: %s occurred at line %d", "file not found", 42)
💻

Example

This example shows how to create and print a formatted error message using fmt.Errorf. It demonstrates passing a string and an integer to format the error text.

go
package main

import (
	"fmt"
)

func main() {
	err := fmt.Errorf("failed to open file %s: error code %d", "data.txt", 404)
	fmt.Println(err)
}
Output
failed to open file data.txt: error code 404
⚠️

Common Pitfalls

Common mistakes when using fmt.Errorf include:

  • Forgetting to use verbs like %s or %d in the format string, which causes the arguments to be ignored.
  • Passing the wrong number or type of arguments, leading to runtime errors.
  • Using errors.New when you need formatted messages, which does not support formatting.

Here is a wrong and right example:

go
package main

import (
	"fmt"
)

func main() {
	// Wrong: no verbs, arguments ignored
	wrongErr := fmt.Errorf("error happened", "extra")
	fmt.Println(wrongErr) // Output: error happened

	// Right: use verbs to include arguments
	rightErr := fmt.Errorf("error: %s", "file missing")
	fmt.Println(rightErr) // Output: error: file missing
}
Output
error happened error: file missing
📊

Quick Reference

Remember these tips when using fmt.Errorf:

  • Use format verbs like %s, %d, %v to insert values.
  • Pass matching arguments for each verb.
  • fmt.Errorf returns an error type with your formatted message.
  • Use it to add context to errors before returning them.

Key Takeaways

Use fmt.Errorf to create formatted error messages with a format string and arguments.
Always include format verbs like %s or %d to insert values into the error message.
fmt.Errorf returns an error type that you can return or handle in your Go code.
Avoid passing arguments without matching verbs, as they will be ignored.
Use fmt.Errorf to add helpful context to errors for easier debugging.