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 , 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.
if resp.StatusCode != 200 {
err = errors.New("response status code != 200")
return
}
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: