Replace errors.New(fmt.Sprintf()) with fmt.Errorf()

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

Metadata

ID: go-best-practices/use-errorf-when-possible

Language: Go

Severity: Warning

Category: Best Practices

Description

In Go, it is recommended to use fmt.Errorf() instead of errors.New(fmt.Sprintf()) for creating error values. The fmt.Errorf() function provides a more expressive and convenient way to generate error values by allowing the formatting of error messages.

Non-Compliant Code Examples

package main

import (
	"errors"
	"fmt"
)

func main() {
	fmt.Println(errors.New(fmt.Sprintf("This is an error")))
}

Compliant Code Examples

package main

import (
	"errors"
	"fmt"
)

func main() {
	fmt.Println(fmt.Errorf("This is an error")))
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: brett0000FF/node-compatibility