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

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: may/unit-testing