使用 io.与无效的作家一起复制,我得到恐慌 - 这是意料之中的。但是,在这种情况下,我无法恢复。我的延迟恢复完全被绕过。代码如下:
package main
import (
"context"
"fmt"
"io"
"log"
"os"
"runtime"
"runtime/debug"
"cloud.google.com/go/storage"
)
func main() {
var (
ctx = context.Background()
fromFile = "blah.txt"
bucket = "blah-bucket"
path = "blah-path"
)
defer func() {
if result := recover(); result != nil {
buf := make([]byte, 1<<16)
length := runtime.Stack(buf, false)
log.Fatalf("PANIC RECOVER: %v\nSTACK: \n%s", result, buf[:length])
debug.PrintStack()
}
}()
err := FakeUpload(ctx, fromFile, bucket, path)
if err != nil {
fmt.Println(err)
}
fmt.Println("HELLO")
}
func FakeUpload(ctx context.Context, fromFile, toBucket, toPath string) (err error) {
var (
file *os.File
client *storage.Client
wc *storage.Writer
)
defer func() {
for _, c := range []io.Closer{wc, file} {
if c != nil {
err = c.Close()
if err != nil {
return
}
}
}
}()
file, err = os.Open(fromFile)
if err != nil {
err = fmt.Errorf("problem opening file %v: %v", fromFile, err)
return
}
wc = client.Bucket(toBucket).Object(toPath).NewWriter(ctx)
_, err = io.Copy(wc, file) // THE UNRECOVERABLE PANIC HAPPENS HERE
return
}
踢球者是,如果它在其他地方恐慌,例如我指向一个无效的文件,它会恐慌,延迟恢复正确捕获它。
这让我感到困惑。有什么想法吗?
喵喵时光机
相关分类