title: How to return custom errors without causing problems with nil values
body: <p>I have implemented a custom error type and do get strange behaviour with regard to nil values. When I do pass the custom error along as standard error interface, this is never recognized as nil, even if the custom error was returned as nil.</p>
  
  <p>Have a look at this little test program:</p>
  
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
      "fmt"
      "strconv"
  )
  
  type CustomError struct {
      Code int
  }
  
  func (e *CustomError) Error() string {
      return strconv.Itoa(e.Code)
  }
  
  func FailCustom(dofail bool) *CustomError {
      if dofail {
          return &amp;CustomError{Code: 42}
      } else {
          return nil
      }
  }
  
  func WrapFailCustom(dofail bool) error {
      return FailCustom(dofail)
  }
  
  func main() {
      err := WrapFailCustom(false)
      if err == nil {
          fmt.Println("err is nil")
      } else {
          fmt.Println("err is not nil")
      }
  }
  </code></pre>
  
  <p>Same in playground: <a href="https://play.golang.org/p/7bqeDw5B5fU" rel="nofollow noreferrer">https://play.golang.org/p/7bqeDw5B5fU</a></p>
  
  <p><strong>This does actually output "err is not nil"</strong>.</p>
  
  <p>I would have expected the nil value of type *CustomError to be implicitly cast to a nil value of type error. Can anybody explain to me, why this is not the case and how to correctly propagate nil values of custom error types?</p>
  
  <p><strong>Edit:</strong>
  Explanation for this can be found <a href="https://golang.org/doc/faq#nil_error" rel="nofollow noreferrer">here</a> as pointed out by Iain Duncan</p>
  
  <p>To further explore the issue, let's consider the following modification to WrapFailCustom:</p>
  
  <pre class="lang-golang prettyprint-override"><code>func WrapFailCustom(dofail bool) error {
      err := FailCustom(dofail)
      if err == nil {
          return nil
      } else {
          return err
      }
  }
  </code></pre>
  
  <p>This does actually return "err is nil": <a href="https://play.golang.org/p/mEKJFyk5zqf" rel="nofollow noreferrer">https://play.golang.org/p/mEKJFyk5zqf</a></p>
  
  <p>I do feel really bad with depending on this as solution, as it is easily forgotten when working with function that do spit out my custom error. Is there better way of making custom errors that does prevent this "ambiguity" from being possible to happen? The obvious solution of just using the basic error type all the time, seems really inconvenient for the code that consumes functions like WrapFailCustom, so I would like to avoid this...</p>