DOKK / manpages / debian 11 / libmojolicious-perl / Mojo::Exception.3pm.en
Mojo::Exception(3pm) User Contributed Perl Documentation Mojo::Exception(3pm)

Mojo::Exception - Exception base class

  # Create exception classes
  package MyApp::X::Foo {
    use Mojo::Base 'Mojo::Exception';
  }
  package MyApp::X::Bar {
    use Mojo::Base 'Mojo::Exception';
  }
  # Throw exceptions and handle them gracefully
  use Mojo::Exception qw(check);
  eval {
    MyApp::X::Foo->throw('Something went wrong!');
  };
  check(
    'MyApp::X::Foo' => sub { say "Foo: $_" },
    'MyApp::X::Bar' => sub { say "Bar: $_" }
  );
  # Generate exception classes on demand
  use Mojo::Exception qw(check raise);
  eval {
    raise 'MyApp::X::Name', 'The name Minion is already taken';
  };
  check(
    'MyApp::X::Name' => sub { say "Name error: $_" },
    default          => sub { say "Error: $_" }
  );

Mojo::Exception is a container for exceptions with context information.

Mojo::Exception implements the following functions, which can be imported individually.

  my $bool = check 'MyApp::X::Foo' => sub {...};
  my $bool = check $err, 'MyApp::X::Foo' => sub {...};

Process exceptions by dispatching them to handlers with one or more matching conditions. Exceptions that could not be handled will be rethrown automatically. By default $@ will be used as exception source, so "check" needs to be called right after "eval". Note that this function is EXPERIMENTAL and might change without warning!

  # Handle various types of exceptions
  eval {
    dangerous_code();
  };
  check(
    'MyApp::X::Foo'     => sub { say "Foo: $_" },
    qr/^Could not open/ => sub { say "Open error: $_" },
    default             => sub { say "Something went wrong: $_" },
    finally             => sub { say 'Dangerous code is done' }
  );

Matching conditions can be class names for ISA checks on exception objects, or regular expressions to match string exceptions and stringified exception objects. The matching exception will be the first argument passed to the callback, and is also available as $_.

  # Catch MyApp::X::Foo object or a specific string exception
  eval {
    dangerous_code();
  };
  check(
    'MyApp::X::Foo'     => sub { say "Foo: $_" },
    qr/^Could not open/ => sub { say "Open error: $_" }
  );

An array reference can be used to share the same handler with multiple conditions, of which only one needs to match. And since exception handlers are just callbacks, they can also throw their own exceptions.

  # Handle MyApp::X::Foo and MyApp::X::Bar the same
  eval {
    dangerous_code();
  };
  check(
    ['MyApp::X::Foo', 'MyApp::X::Bar'] => sub { die "Foo/Bar: $_" }
  );

There are currently two keywords you can use to set special handlers. The "default" handler is used when no other handler matched. And the "finally" handler runs always, it does not affect normal handlers and even runs if the exception was rethrown or if there was no exception to be handled at all.

  # Use "default" to catch everything
  eval {
    dangerous_code();
  };
  check(
    default => sub { say "Error: $_" },
    finally => sub { say 'Dangerous code is done' }
  );

  raise 'Something went wrong!';
  raise 'MyApp::X::Foo', 'Something went wrong!';

Raise a Mojo::Exception, if the class does not exist yet (classes are checked for a "new" method), one is created as a Mojo::Exception subclass on demand. Note that this function is EXPERIMENTAL and might change without warning!

Mojo::Exception implements the following attributes.

  my $frames = $e->frames;
  $e         = $e->frames([$frame1, $frame2]);

Stack trace if available.

  # Extract information from the last frame
  my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext,
      $is_require, $hints, $bitmask, $hinthash) = @{$e->frames->[-1]};

  my $line = $e->line;
  $e       = $e->line([3, 'die;']);

The line where the exception occurred if available.

  my $lines = $e->lines_after;
  $e        = $e->lines_after([[4, 'say $foo;'], [5, 'say $bar;']]);

Lines after the line where the exception occurred if available.

  my $lines = $e->lines_before;
  $e        = $e->lines_before([[1, 'my $foo = 23;'], [2, 'my $bar = 24;']]);

Lines before the line where the exception occurred if available.

  my $msg = $e->message;
  $e      = $e->message('Died at test.pl line 3.');

Exception message, defaults to "Exception!".

  my $bool = $e->verbose;
  $e       = $e->verbose($bool);

Show more information with "to_string", such as "frames", defaults to the value of the "MOJO_EXCEPTION_VERBOSE" environment variable.

Mojo::Exception inherits all methods from Mojo::Base and implements the following new ones.

  $e = $e->inspect;
  $e = $e->inspect($source1, $source2);

Inspect "message", "frames" and optional additional sources to fill "lines_before", "line" and "lines_after" with context information.

  my $e = Mojo::Exception->new;
  my $e = Mojo::Exception->new('Died at test.pl line 3.');

Construct a new Mojo::Exception object and assign "message" if necessary.

  my $str = $e->to_string;

Render exception. Note that the output format may change as more features are added, only the error message at the beginning is guaranteed not to be modified to allow regex matching.

  Mojo::Exception->throw('Something went wrong!');

Throw exception from the current execution context.

  # Longer version
  die Mojo::Exception->new('Something went wrong!')->trace;

  $e = $e->trace;
  $e = $e->trace($skip);

Generate stack trace and store all "frames", defaults to skipping 1 call frame.

  # Skip 3 call frames
  $e->trace(3);
  # Skip no call frames
  $e->trace(0);

Mojo::Exception overloads the following operators.

  my $bool = !!$e;

Always true.

  my $str = "$e";

Alias for "to_string".

Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.

2021-01-24 perl v5.32.0