[Golang] Create Error Using fmt.Errorf or errors.New


In Go, we have two easy methods to create new or custom error - either errors.New or fmt.Errorf in Go standard library. According to discussion in reddit [2], these two methods are identical except fmt.Errorf allows you to format error message string. We will illustrate the difference by the example of handing HTTP response status code.

errors.New

if resp.StatusCode != 200 {
      err = errors.New("response status code != 200")
      return
}

fmt.Errorf

if resp.StatusCode != 200 {
      err = fmt.Errorf("response status code: %d", resp.StatusCode)
      return
}

As you can see from the above two code snippets, errors.New returns only a fixed string of error message, while fmt.Errorf returns a variable string of error message which tells the staus code of the HTTP response. This example illustrates the difference of errors.New and fmt.Errorf.


References:

[1]golang fmt.errorf at DuckDuckGo
[2]fmt.Errorf() or errors.New()? : golang
[3]"Errors in Go: From denial to acceptance". A practical guide to error handling patterns in Golang. : golang
[4]Error Values — Problem Overview : golang
[5]How to handle errors in a live application? : golang