NAME

Perinci::Sub::Util - Helper when writing functions

VERSION

version 0.37

SYNOPSIS

use Perinci::Sub::Util qw(err caller);

sub foo {
    my %args = @_;
    my $res;

    my $caller = caller();

    $res = bar(...);
    return err($err, 500, "Can't foo") if $res->[0] != 200;

    [200, "OK"];
}

FUNCTIONS

caller([ $n ])

Just like Perl's builtin caller(), except that this one will ignore wrapper code in the call stack. You should use this if your code is potentially wrapped. See Perinci::Sub::Wrapper for more details.

err(...) => ARRAY

Experimental.

Generate an enveloped error response (see Rinci::function). Can accept arguments in an unordered fashion, by utilizing the fact that status codes are always integers, messages are strings, result metadata are hashes, and previous error responses are arrays. Error responses also seldom contain actual result. Status code defaults to 500, status message will default to "FUNC failed". This function will also fill the information in the logs result metadata.

Examples:

err();    # => [500, "FUNC failed", undef, {...}];
err(404); # => [404, "FUNC failed", undef, {...}];
err(404, "Not found"); # => [404, "Not found", ...]
err("Not found", 404); # => [404, "Not found", ...]; # order doesn't matter
err([404, "Prev error"]); # => [500, "FUNC failed", undef,
                          #     {logs=>[...], prev=>[404, "Prev error"]}]

Will put stack_trace in logs only if Carp::Always module is loaded.

FAQ

What if I want to put result ($res->[2]) into my result with err()?

You can do something like this:

my $err = err(...) if ERROR_CONDITION;
$err->[2] = SOME_RESULT;
return $err;

SEE ALSO

Perinci::Util

Perinci

AUTHOR

Steven Haryanto <stevenharyanto@gmail.com>

COPYRIGHT AND LICENSE

This software is copyright (c) 2013 by Steven Haryanto.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.