A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

A good try/catch pattern for exceptions and failures

This Perl code neatly captures (1) unexpected exceptions, and (2) expected failures:
use Try::Tiny; # the best try/catch module
use Data::Dumper::Concise;
my ( $response, $response_error );
try {
$response = method_call_that_might_not_work()
}
catch($action_error) {
# Method call died and did not complete
$response_error = $action_error;
};
# Method call completed, but was not successful
$response_error ||= $response->{error};
if ($response_error) {
# Check the data dump is suitable for logging
$log->warn("Response failed with '$response_error': ".Dumper($response);
# Response to client
$c->render( status => 500, text => "Internal Server Error" );
return;
}
view raw try_catch.pl hosted with ❤ by GitHub

Add headers or cookies to request in Mojolicious tests

When using Test::Mojo, sometimes you want to modify the request to add a cookie or custom headers.

# Define app
my $t = Test::Mojo->new("Test::App");
# Build request with custom headers
my %headers = ( 'X-Auth-Signature' => 'abcdef' );
my $tx = $t->ua->build_tx(POST => '/api/boards' => \%headers => json => { username => 'testuser' } );
# Add cookie
$tx->req->cookies({ name => 'cookie1', value => $jwt });
# Perform test
$t->request_ok($tx)->status_is(200);
.