Evan Carroll
Evan Carroll

Reputation: 1

How do I redirect in a Mojo::Exception check block?

Let's say I have something like this which works,

eval { die "asdf" }
Mojo::Exception::check(
    default => sub { die 42 }
);

But what I want is something like this..

eval { die "asdf" }
Mojo::Exception::check(
    default => sub { $c->redirect_to("https://google.com") }
);

I find that even up the completion of the $c->redirect_to that nothing happens. Moreover, if I do something like,

eval { die "asdf" }
Mojo::Exception::check(
    default => sub { $c->redirect_to("https://google.com"); die 42; }
);

That it still dies.

So in normal code I can do

return $c->redirect_to("https://google.com");

Which will work, but how do I do that inside of a call to Mojo::Exception::check

Upvotes: 1

Views: 210

Answers (2)

Grinnz
Grinnz

Reputation: 9231

I would prefer to use Syntax::Keyword::Try to catch exceptions. This solves this problem, because it does not wrap the exception handler in a subroutine so you can simply return, as well as by default avoiding the issue of relying on truthiness of $@.

use strict;
use warnings;
use Syntax::Keyword::Try;

sub ... {
  try { die "asdf" }
  catch { return $c->redirect_to("https://google.com"); }
}

Upvotes: 2

Evan Carroll
Evan Carroll

Reputation: 1

I got around this by adding,

return $c if $c->res->is_redirect

Like this,

eval { die "asdf" }
Mojo::Exception::check(
    default => sub { $c->redirect_to("https://google.com"); }
);
return $c if $c->res->is_redirect;

Also,

09:16 < kraih> EvanCarroll: best is probably "return if $c->res->code;"

Upvotes: 1

Related Questions