perl - 在现代 Perl 中编写异常类的最佳实践

标签 perl exception

Exception::Class ,我可以将异常定义为类,一旦它们被加载到任何地方,它们就随处可用。但是很多地方,包括 E::C 本身的文档,都建议使用 Throwable。现在。

Throwable 是一个角色,因此我需要构建类以将其组合到其中。 Throwable::Factory对此有所帮助,但我不知道如何使这些类随处可用。似乎 T::F 构建了返回不透明类名的子例程。我觉得我错过了最后一 block 拼图,但无法找到 T::F 实际使用的任何示例。

最佳答案

一个想法可能是在一个单独的模块中收集异常并将其导入到需要访问异常的所有模块中。不幸的是,由于某种原因似乎很难导出这些。我尝试了以下 (MyExceptions.pm):

package MyExceptions;
use Throwable::Factory
  GeneralException => undef,
  RuntimeException => undef,
;
our @EXPORT = qw(GeneralException RuntimeException);
sub import2 {
    no strict 'refs';

    my $caller = caller;
    my $pkg = __PACKAGE__;
    for my $name (@EXPORT) {
        my $imported = $caller . '::' . $name;
        my $coderef = *{$pkg . "::" . $name};
        *{ $imported } = \*{ $coderef };
    }
}

sub import {
    no strict 'refs';

    my $caller = caller;
    my $pkg = __PACKAGE__;
    my @coderefs = (
        ["GeneralException", *MyExceptions::GeneralException],
        ["RuntimeException", *MyExceptions::RuntimeException]
    );
    for my $item (@coderefs) {
        my ($name, $coderef) = @$item;
        my $imported = $caller . '::' . $name;
        *{ $imported } = \*{ $coderef };
    }
}

1;

我无法使上面代码中的 import2() exporter sub 工作(它不导出异常,而是导出其他东西(但是什么?)) ,因此作为一种解决方法,我编写了有效的 import() sub。

关于perl - 在现代 Perl 中编写异常类的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69729489/

相关文章:

php - 有效电子邮件地址的 Swift_RfcComplianceException,适用于 Windows 而不是 Ubuntu

.net - Source=null 的 ImageSourceConverter 错误

perl - 执行使用 Elasticsearch.pm 的 perl 脚本时,Module/Runtime.pm 的版本格式无效(需要版本)

java - Spring MVC Controller 代码 : getOutputStream() has already been called for this response

perl - 使用 WWW::Mechanize,如何添加带下划线的小写标题?

perl - 使用标志使 Perl 脚本 * 自行运行 *

java - 异常处理什么时候用catch,什么时候用throws

PHP:异常未被 try ... catch 捕获

perl - 在继承函数中访问类变量?

perl - 在5.6.x之后不赞成使用Perl的-w开关来警告吗?