exception handling with async/await #2086
-
In Mojolicious full app, I have the following pattern.
Using package Octopus::Controller::MyController;
use Mojo::Base 'Mojolicious::Controller', -signatures, -async_await;
async sub add_db1($self, $table1_locationA, $table1_locationB, $table2) {
my @table1 = await Mojo::Promise->all( map { $self->db1->LocationA_p($_), $self->db1->LocationB_p($_) } @$table1_locationA, @$table1_locationB );
my @table2 = await Mojo::Promise->all( map { $self->db1->LocationA_p($_), $self->db1->LocationB_p($_) } @$table2 );
return (@table1, @table2);
}
async sub add_db2($self, $table1, $table2) {
my @table1 = await Mojo::Promise->all( map { $self->db2->LocationA_p($_), $self->db2->LocationB_p($_) } @$table1 );
my @table2 = await Mojo::Promise->all( map { $self->db2->LocationA_p($_), $self->db2->LocationB_p($_) } @$table2 );
return (@table1, @table2);
}
async sub add_db_v1 ($self) {
my $app = $self->openapi->valid_input or return;
my $input = $app->validation->output;
my $body = $input->{body};
my $param = $body->{'param'};
my ($table1_locationA, $table1_locationB, $table1, $table2);
push @$table1_locationA, qq(ADD SOMETHING:PARAM=A"${param}";);
push @$table1_locationB, qq(ADD SOMETHING:PARAM=B"${param}";);
push @$table1 , qq(ADD SOMETHING:PARAM=1"${param}";);
push @$table2 , qq(ADD SOMETHING:PARAM=2"${param}";);
$self->render_later();
my @results = await Mojo::Promise->all(
$self->add_db1($table1_locationA, $table1_locationB, $table2),
$self->add_db2($table1, $table2),
);
foreach my $response (@results) {
# do something with each $response, construct $message
}
$app->render(openapi => {messages=>$messages} );
}
1; I tried the following:
my @results = await Mojo::Promise
->all(
$self->add_db1($table1_locationA, $table1_locationB, $table2),
$self->add_db2($table1, $table2),
)
->catch(sub ($err) {
warn "Something went wrong: " . dumper($err);
$app->render(openapi => {error=>$err}, status=>502 );
});
my @results = eval { await Mojo::Promise->all(
$self->add_db1($table1_locationA, $table1_locationB, $table2),
$self->add_db2($table1, $table2),
)};
if (my $err = $@) {
warn "Something went wrong: " . dumper($err);
$app->render(openapi => {error=>$err}, status=>502 );
}
else {
foreach my $response (@results) {
# do something with each $response, construct $message
}
$app->render(openapi => {messages=>$messages} );
} Your feedback and input is highly appreciated. Thank you! P.S. My helper looks like: async sub LocationA_p($self, $request)
{
return Mojo::Promise->new(sub($resolve, $reject ) {
Mojo::IOLoop->subprocess(
sub {
$self->lgeacy($request);
},
sub {
my ( $subprocess, $err, @res ) = @_;
$reject->( $err ) if $err;
$resolve->( @res );
});
});
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The normal exception handling mechanism for an |
Beta Was this translation helpful? Give feedback.
The normal exception handling mechanism for an
await
is a plain oldtry
/catch
.