Diane Diane - 3 days ago 4
Perl Question

Perl Net::Stripe Internal Server Error with Bad Credit Card Number

I am using Net::Stripe to process credit cards. It is working correctly if the credit card number is valid. But when I test a bad credit card number, I get to line 676 of Stripe.pm:

676: die $e;


and that produces this error:


1 at /usr/share/perl/5.14/perl5db.pl line 7799.


which causes an Internal Server Error in the browser.

The block of code in Stripe.pm that ends with the die statement is this:

if ($resp->code == 200) {
return _hash_to_object(decode_json($resp->content));
} elsif ($resp->code == 500) {
die Net::Stripe::Error->new(
type => "HTTP request error",
code => $resp->code,
message => $resp->status_line . " - " . $resp->content,
);
}

my $e = eval {
my $hash = decode_json($resp->content);
Net::Stripe::Error->new($hash->{error})
};
if ($@) {
Net::Stripe::Error->new(
type => "Could not decode HTTP response: $@",
message => $resp->status_line . " - " . $resp->content,
);
};

warn "$e\n" if $self->debug;
die $e;


The response code that is being returned from Stripe is 402.

I am trying to handle error messages from Stripe with the following code:

my $card_token = $stripe->post_token(
card => {
number => $FORM{'Credit Card #'},
exp_month => $FORM{'Expiration Month'},
exp_year => $FORM{'Expiration Year'},
currency => 'usd',
cvc => $FORM{'Credit Card Security Code'},
name => $FORM{'Name on Card'},
address_line1 => $FORM{'Address'},
address_city => $FORM{'City'},
address_state => $FORM{'State'},
address_zip => $FORM{'Zip'}
}
);

if ($card_token->{failure_message}) {

$error = $card_token->{failure_message};

print "Content-type: text/html\n\n";
print "There was an error processing your credit card:<br><br>$error";

}


But the code is dying before it exits the block of code that is trying to retrieve the token.

Is there a way to suppress that "die" statement?

Answer

You can use eval to trap this exception, then carry on working.

my $card_token;

my $ok = eval {
    $card_token = $stripe->post_token(
        card => {
            number    => $FORM{'Credit Card #'},
            exp_month => $FORM{'Expiration Month'},
            exp_year  => $FORM{'Expiration Year'},
            currency  => 'usd',
            cvc       => $FORM{'Credit Card Security Code'},
            name      => $FORM{'Name on Card'},
            address_line1  => $FORM{'Address'},
            address_city  => $FORM{'City'},
            address_state  => $FORM{'State'},
            address_zip  => $FORM{'Zip'}
        }
    );

    1;
}

if (! $ok) {
    # error object is in $@. You'll need to investigate its structure
    # before using it

    my $error = $@;

    ...;
}
else {
    # do stuff with $card_token
}
Comments