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

标签 go error-handling base64

考虑这个简单的 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))
}

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

const encoded string = "XXXXXaGVsbG8="

然后我点击了 panic 线,这给了我:

panic: illegal base64 data at input byte 11

goroutine 1 [running]:
main.main()
    /tmp/sandbox422941756/main.go:12 +0x140

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

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

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

最佳答案

查看错误类型。例如,

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))
}

输出:

panic: 
base64 input is corrupt, check service Key

关于go - 在 Go 中处理来自 base64 解码的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870022/

相关文章:

openssl生成指纹的Ruby代码

go - 我们可以通过反射更新结构字段上的标签吗?

git - 使用 go 语言与 gitolite

php - PHP-自定义验证器函数并传递未设置的变量

swift - 在Swift中向用户显示网络错误消息

python - base64 编码字节 v b64encode v 编码字符串

go - 奇怪的编译错误说 'no buildable Go source files'

go - 如何正确处理 runtime.Caller(0) 上的错误

r - 使用方法错误("select_"): no applicable method for 'select_' applied to an object of class "character"

node.js - golang base64 编码 vs nodejs 缓冲区 base64 编码