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

Mojo::Exception - Exceptions with context

  use Mojo::Exception;
  # Throw exception and show stack trace
  eval { Mojo::Exception->throw('Something went wrong!') };
  say "$_->[1]:$_->[2]" for @{$@->frames};
  # Customize exception
  eval {
    my $e = Mojo::Exception->new('Died at test.pl line 3.');
    die $e->trace(2)->inspect->verbose(1);
  };
  say $@;

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

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

Enable context information for "to_string".

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.

  # Render exception with context
  say $e->verbose(1)->to_string;

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

Throw exception from the current execution context.

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

  $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>.

2019-02-05 perl v5.28.1