考虑这个简单的 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 code和 this 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/