在Golang中导入模块时如何捕获错误? [英] How to capture errors when importing a module in Golang?

查看:46
本文介绍了在Golang中导入模块时如何捕获错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在golang中,当我导入一个模块时,它的init()被执行(假设在main()之前?),此函数可能会生成一些错误.我该如何捕获这些错误并以自己的代码进行处理?

In golang, when I import a module, its init() gets executed (before main() I assume?), it is possible some error is generated in this function. How can I capture these errors and handle them in my own code?

推荐答案

是的,将包 init()函数运行在 main()函数之前,请参见语言规范中的包初始化.

Yes, package init() functions run before the main() function, see Package initialization in the language specification.

不,您不能处理程序包 init()函数中发生的错误.即使可以,这也意味着程序依赖的程序包初始化失败,并且您不知道从中得到什么.

And no, you can't handle errors occurred in package init() functions. Even if you could, that would mean a package your program depends on failed to initialize and you wouldn't know what to expect from it.

Package init()函数没有返回值,因此无法以有意义的方式惊慌,而这本来是可以恢复的.如果 init()函数出现紧急情况,程序将终止.

Package init() functions have no return values and they can't panic in a meaningful way that was meant to recover from. If an init() function panics, the program terminates.

由于您未调用 init()函数(例如,从 main()函数调用),因此无法从那里恢复.程序包本身有责任在初始化期间处理错误,而不是程序包的用户.

Since init() functions are not called by you (e.g. from the main() function), you can't recover from there. It is the responsibility of the package itself to handle errors during its initialization, not the users of the package.

一种表示在 init()期间发生错误的信号的选项是将错误状态存储在变量中(例如,已导出或未导出,但可通过导出的函数查询).但这仅在合理的情况下才可以继续使用,并且这也是包本身(存储/报告错误)的任务/职责,而不是包的用户.没有软件包的配合,您将无法做到这一点(您无法捕获"未处理/未报告的错误和恐慌).

One option to signal error happening during an init() is to store the error state in a variable (e.g. exported, or unexported but queryable by an exported function). But this should be used only if it is reasonable to continue, and this is also the task/responsibility of the package itself (to store/report the error) and not the users of the package. You can't do this without the cooperation of the package (you can't "catch" unhandled/unreported errors and panics).

这篇关于在Golang中导入模块时如何捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆