在 Go 中处理来自 base64 解码的错误

evi*_*obu 3 error-handling base64 go

考虑这个简单的 base64 解码片段:

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))
}
Run Code Online (Sandbox Code Playgroud)

这会按预期产生hello。现在,如果我故意传入损坏的输入,例如

const encoded string = "XXXXXaGVsbG8="
Run Code Online (Sandbox Code Playgroud)

然后我点击了恐慌线,这给了我:

panic: illegal base64 data at input byte 11

goroutine 1 [running]:
main.main()
    /tmp/sandbox422941756/main.go:12 +0x140
Run Code Online (Sandbox Code Playgroud)

查看源代码这个问题,除了匹配字符串文字并向调用者返回更有意义的错误消息之外,这里似乎没有什么可做的:

if err != nil {
    if strings.Contains(err.Error(), "illegal base64 data at input byte") {
        panic("\nbase64 input is corrupt, check service Key")
    }
}
Run Code Online (Sandbox Code Playgroud)

除了字符串匹配之外,必须有一种更优雅的方法来做到这一点。实现这一目标的go- esque方法是什么?

pet*_*rSO 5

查看错误类型。例如,

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    encoded := "XXXXXaGVsbG8=" // corrupt
    decoded, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
        if _, ok := err.(base64.CorruptInputError); ok {
            panic("\nbase64 input is corrupt, check service Key")
        }
        panic(err)
    }
    fmt.Println(string(decoded))
}
Run Code Online (Sandbox Code Playgroud)

输出:

panic: 
base64 input is corrupt, check service Key
Run Code Online (Sandbox Code Playgroud)