栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在golang中捕获panic()

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在golang中捕获panic()

据我所知,您无法将恐慌的输出重定向到标准错误或记录器。最好的办法是将标准错误重定向到可以在外部或在程序内部执行的文件。

对于我的rclone程序,我重定向了标准错误,以将所有内容捕获到一个选项上的文件中,但是不幸的是,以跨平台的方式并不是一件容易的事。这是我的操作方法(请参阅redirect* .go文件)

对于linux / unix

// Log the panic under unix to the log file//+build unixpackage mainimport (    "log"    "os"    "syscall")// redirectStderr to the file passed infunc redirectStderr(f *os.File) {    err := syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd()))    if err != nil {        log.Fatalf("Failed to redirect stderr to file: %v", err)    }}

和窗户

// Log the panic under windows to the log file//// Code from minix, via//// http://play.golang.org/p/kLtct7lSUg//+build windowspackage mainimport (    "log"    "os"    "syscall")var (    kernel32         = syscall.MustLoadDLL("kernel32.dll")    procSetStdHandle = kernel32.MustFindProc("SetStdHandle"))func setStdHandle(stdhandle int32, handle syscall.Handle) error {    r0, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0)    if r0 == 0 {        if e1 != 0 { return error(e1)        }        return syscall.EINVAL    }    return nil}// redirectStderr to the file passed infunc redirectStderr(f *os.File) {    err := setStdHandle(syscall.STD_ERROR_HANDLE, syscall.Handle(f.Fd()))    if err != nil {        log.Fatalf("Failed to redirect stderr to file: %v", err)    }    // SetStdHandle does not affect prior references to stderr    os.Stderr = f}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507002.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号