title: Handling errors from base64 decode in Go
body: <p>Consider this simple base64 decode snippet:</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "encoding/base64"
  )
  
  func main() {
      const encoded string = "aGVsbG8=" // hello
      decoded, err := base64.StdEncoding.DecodeString(encoded)
      if err != nil {
          panic(err)
      }
      fmt.Println(string(decoded))
  }
  </code></pre>
  
  <p>This produces <em>hello</em> as expected.
  Now, if i intentionally pass in corrupt input, e.g.</p>
  
  <pre><code>const encoded string = "XXXXXaGVsbG8="
  </code></pre>
  
  <p>then i hit the panic line which gives me:</p>
  
  <pre><code>panic: illegal base64 data at input byte 11
  
  goroutine 1 [running]:
  main.main()
      /tmp/sandbox422941756/main.go:12 +0x140
  </code></pre>
  
  <p>Looking at the <a href="https://github.com/golang/go/issues/10290" rel="nofollow noreferrer">source code</a> and <a href="https://github.com/golang/go/issues/10290" rel="nofollow noreferrer">this issue</a>, seems there is not much to go by here other than matching the string literal and returning a more meaningful error message to the caller:</p>
  
  <pre><code>if err != nil {
      if strings.Contains(err.Error(), "illegal base64 data at input byte") {
          panic("\nbase64 input is corrupt, check service Key")
      }
  }
  </code></pre>
  
  <p>There has to be a more elegant way to do this other than string matching.
  What is the <strong>go</strong>-esque way to achieve this?</p>