How to separate error handling from business logic in Perl?

How to separate exception handling / error handling from business logic? I write code in Perl, and error / exception handling and business logic make it very difficult to understand the code when viewing it.

How can I reorganize my code to make it more readable, but with error handling. Also note that I am not using try catch or anything like that.

One of our senior programmers suggested that we again open the standard OS error and write everything there, and we can catch it as the caller.

Edit: this is how I do error handling. I have many Perl modules. socheck2.pm

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

and I use it like in my Perl script, check.pl

In my Perl script

#!/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" ;
}

It would be very helpful if someone could help me point out errors in this.

+3
3

,

 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;
}

" " , .

, . , , . ( ... Perl . , ... - .)

+3

, , , -, , - .

, -, -. , , .

, -.

0

? , ?

perl . , open(my $filehandle, '>', $filename) or die "Failed to open $filename" . , autodie, .

One of our senior programmers suggested that we again open the standard OS error and write everything there, and we can catch it as the caller.

This is better than nothing, I suppose, but don't stop there. Completing all the code in one cycle (1) and the giant try / catch won't let you do anything complicated, plus one huge code smell.

Finally:

Notice that I do not use try catch or anything like that.

Why not?

0
source

Source: https://habr.com/ru/post/1719249/


All Articles