Mojo::Exception(3)

🌸 NAME 🌸

Mojo::Exception(3) is the exception base class from User Contributed Perl Documentation, bestie 🫢. She’s lowkey just a container for exceptions with context information, but make it fashion. ✨

✨ SYNOPSIS ✨

okay bestie, here’s the vibe: create exception classes, throw them, handle them gracefully, and even generate them on demand. no cap, the code is right here πŸ’…

# 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: $_" }
];

πŸ’– DESCRIPTION πŸ’–

Mojo::Exception is a container for exceptions with context information. That’s the whole assignment, and she ate. πŸ’…

🫢 FUNCTIONS 🫢

Mojo::Exception implements these functions, and you can import each one individually, iykyk ✨

πŸŽ€ check

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 β€” no silent swallowing, periodt πŸ’€

# 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: $_" }
];

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 $_ β€” main character gets both seats πŸ‘‘πŸŒΈ

# 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. messy? maybe, but valid πŸ’€

# 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 is currently only one keyword you can use to set special handlers. The "default" handler is used when no other handler matched. It’s the safety net, the group-chat lurker, the final boss 🌈

# Use "default" to catch everything
eval {
  dangerous_code();
};
check $@ => [
  default => sub { say "Error: $_" }
];

🐚 raise

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. on-demand class generation? iconic ✨

πŸ¦‹ ATTRIBUTES πŸ¦‹

Mojo::Exception implements these attributes. They’re the little details that give the exception its whole vibe πŸ’–

🧚 frames

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

Stack trace if available. That’s the receipts 🧾

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

🌸 line

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

The line where the exception occurred if available. she’s pointing at the scene of the crime πŸ’…

πŸ“ lines_after

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. the aftermath, the sequel, the plot twist 😭

πŸŽ€ lines_before

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. the prequel, the context, the lore 🌸

πŸ’œ message

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

Exception message, defaults to "Exception!". If it’s not the drama, it’s at least the text πŸ’€

🌈 verbose

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. yes bestie, environment variable, it’s giving configurable πŸ’…

πŸ‘‘ METHODS πŸ‘‘

Mojo::Exception inherits all methods from Mojo::Base and implements these new ones. slay ✨

πŸ”₯ inspect

$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. It’s basically doing a vibe check on the source 🫢

⭐ new

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. fresh object, new me, same exception energy πŸ’…

🌸 to_string

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. so do not build your entire personality on the full format, bestie, just the first bit 😭

πŸŽ€ throw

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

Throw exception from the current execution context. dramatic? yes. necessary? also yes πŸ’€

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

πŸ¦‹ trace

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

Generate stack trace and store all frames, defaults to skipping 1 call frame. choose your skip count, choose your destiny ✨

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

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

🌈 OPERATORS 🌈

Mojo::Exception overloads these operators. fancy πŸ’…

πŸ’– bool

my $bool = !!$e;

Always true. no notes. she’s always that girl πŸ‘‘

πŸŽ€ stringify

my $str = "$e";

Alias for to_string. same energy, different syntax ✨

πŸ’œ SEE ALSO πŸ’œ

Mojolicious, Mojolicious::Guides, <https://mojolicious.org>. go read, bestie, iykyk πŸ“š


mwah πŸ’‹ β€” this tea was served by perl v5.42.0 on 2026-07-15. now go handle those exceptions with grace πŸ’…βœ¨

πŸ“¦ where this page comes from