This product is not supported for your selected Datadog site. ().
이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다. 현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.
Metadata
ID:go-best-practices/errors-new-errorf
Language: Go
Severity: Info
Category: Best Practices
Description
You should use fmt.Errorf("something %w", foo) instead of errors.New(fmt.Sprintf("something %s", foo)).
Here are a few reasons why:
Error wrapping: By using fmt.Errorf with the %w format specifier instead of %s, your new error object wraps the original error. This makes it possible to access the original error object using errors.Is and errors.As.
Simplicity: The fmt.Errorf function simplifies the error message creation by combining the formatting and error wrapping in one function call. In contrast, using errors.New(fmt.Sprintf("something %s", foo)) requires an extra step of formatting the string separately before creating the error.
Consistency: By consistently using fmt.Errorf, developers maintain a uniform approach to error handling and can easily recognize and handle errors throughout the codebase. Using a single idiomatic method rather than mixing different styles ensures consistency and improves code readability and maintainability.