ErrorHandling.pm 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # This program is free software; you can redistribute it and/or modify
  2. # it under the terms of the GNU General Public License as published by
  3. # the Free Software Foundation; either version 2 of the License, or
  4. # (at your option) any later version.
  5. #
  6. # This program is distributed in the hope that it will be useful,
  7. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. # GNU General Public License for more details.
  10. #
  11. # You should have received a copy of the GNU General Public License
  12. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. package Dpkg::ErrorHandling;
  14. use strict;
  15. use warnings;
  16. our $VERSION = '0.02';
  17. our @EXPORT_OK = qw(
  18. report
  19. );
  20. our @EXPORT = qw(
  21. report_options
  22. info
  23. warning
  24. error
  25. errormsg
  26. syserr
  27. subprocerr
  28. usageerr
  29. );
  30. use Exporter qw(import);
  31. use Dpkg ();
  32. use Dpkg::Gettext;
  33. my $quiet_warnings = 0;
  34. my $info_fh = \*STDOUT;
  35. sub report_options
  36. {
  37. my (%options) = @_;
  38. if (exists $options{quiet_warnings}) {
  39. $quiet_warnings = $options{quiet_warnings};
  40. }
  41. if (exists $options{info_fh}) {
  42. $info_fh = $options{info_fh};
  43. }
  44. }
  45. sub report(@)
  46. {
  47. my ($type, $msg) = (shift, shift);
  48. $msg = sprintf($msg, @_) if (@_);
  49. return "$Dpkg::PROGNAME: $type: $msg\n";
  50. }
  51. sub info($;@)
  52. {
  53. print { $info_fh } report(g_('info'), @_) if (!$quiet_warnings);
  54. }
  55. sub warning($;@)
  56. {
  57. warn report(g_('warning'), @_) if (!$quiet_warnings);
  58. }
  59. sub syserr($;@)
  60. {
  61. my $msg = shift;
  62. die report(g_('error'), "$msg: $!", @_);
  63. }
  64. sub error($;@)
  65. {
  66. die report(g_('error'), @_);
  67. }
  68. sub errormsg($;@)
  69. {
  70. print { *STDERR } report(g_('error'), @_);
  71. }
  72. sub subprocerr(@)
  73. {
  74. my ($p) = (shift);
  75. $p = sprintf($p, @_) if (@_);
  76. require POSIX;
  77. if (POSIX::WIFEXITED($?)) {
  78. error(g_('%s gave error exit status %s'), $p, POSIX::WEXITSTATUS($?));
  79. } elsif (POSIX::WIFSIGNALED($?)) {
  80. error(g_('%s died from signal %s'), $p, POSIX::WTERMSIG($?));
  81. } else {
  82. error(g_('%s failed with unknown exit code %d'), $p, $?);
  83. }
  84. }
  85. my $printforhelp = g_('Use --help for program usage information.');
  86. sub usageerr(@)
  87. {
  88. my ($msg) = (shift);
  89. $msg = sprintf($msg, @_) if (@_);
  90. warn "$Dpkg::PROGNAME: $msg\n\n";
  91. warn "$printforhelp\n";
  92. exit(2);
  93. }
  94. 1;