gpt4 book ai didi

perl - 如何在 Perl 中将错误处理与业务逻辑分开?

转载 作者:行者123 更新时间:2023-12-02 13:49:01 26 4
gpt4 key购买 nike

如何将异常处理/错误处理与业务逻辑分开?我正在用 Perl 编写代码,错误/异常处理和业务逻辑使得在检查时理解代码变得非常困难。

如何重构我的代码以使其更具可读性并具有错误处理功能。另请注意,我不使用 try catch 或类似的东西。

我们的一位高级程序员建议我们重新打开操作系统标准错误并将所有内容写入其中,以便调用者可以捕获它。

编辑:这是我如何进行错误处理。我有很多 Perl 模块..所以 check2.pm

package check2;
sub printData {
print STDERR "Error Message from sub routine \n";
}
1;

我在我的 Perl 脚本中像这样使用它,check.pl

在我的 Perl 脚本中

#!/usr/bin/perl
use LoadModules;
use strict;
use warnings;

load check2;

my $stderrholder;
local *SAVEERR;

# First, save existing STDERR
open SAVEERR, ">&STDERR" or print "not able to open";
close STDERR;

# Open the STDERR to a variable
open STDERR, ">", \$stderrholder or die "Failed to reopen STDERR $!\n";

#Start of processing

# Now print something to STDERR, redirected to $ stderrholder
print STDERR " Error Message from Main script \n";

check2::printData();

#End of processing

# Now close and restore STDERR to original condition.
close STDERR;
#open STDERR, ">&SAVEERR";

# Now check if there were any processing errors.
if(length($stderrholder)) {
print "\nProcessing errors\n" ;
if(length($stderrholder)) {
print "\nProcessing errors\n" ;
print $stderrholder;
} else {
print "\nNo Processing errors\n" ;
}

如果有人能帮助我指出其中的错误,我将不胜感激。

最佳答案

导致错误的代码

 sub whatever { 
die "OH NOES" if an_error($occurred);
}

您的主程序:

 use Try::Tiny; # essential
my $logger = anything_you_want;
try {
whatever;
}
catch {
$logger->error("Error: $_");
};

出现问题时抛出异常。在任何有意义的地方处理异常;通常在顶层。

有时你可以“修复”异常;示例:如果主服务器不可用,则连接到故障转移服务器。在这种情况下,请在比顶级应用程序更高级别但比“connect”函数更近的地方处理故障转移:

sub connect {
die "Error connecting: ..." if ...;
}

sub make_connection {
my $connection = try { connect($main_server) };
$connection ||= try { connect($backup_server) };
die "Couldn't connect to either server" unless $connection;
return $connection;
}

然后,您将在顶级代码中处理“无法连接到任一服务器”,而不是处理每个单独的连接错误。

最后,您还可以使用 Error monad 。这允许您返回失败代码,但它确保失败后不会执行任何代码。 (这种方法更适合基于异步事件的代码...但大多数 Perl 程序员不喜欢 monad,而是尝试对所有内容使用异常。不过,这很好...异常是处理错误的好方法。)

关于perl - 如何在 Perl 中将错误处理与业务逻辑分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1518332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com