JSON-API-Error

 view release on metacpan or  search on metacpan

lib/JSON/API/Error.pm  view on Meta::CPAN

package JSON::API::Error;

# ABSTRACT: JSON API-style error objects

use Moo;
use overload bool => sub {1}, '""' => \&to_string;

use Types::Standard qw/Str HashRef/;

our $VERSION = '0.01';

has code   => (is => 'ro', isa => Str);
has detail => (is => 'ro', isa => Str);
has id     => (is => 'ro', isa => Str);
has links  => (is => 'ro', isa => HashRef);
has meta   => (is => 'ro', isa => HashRef);
has source => (is => 'ro', isa => HashRef);
has status => (is => 'ro', isa => Str);
has title  => (is => 'ro', isa => Str);

sub to_string {
    my $self = shift;
    return sprintf "%s: %s", $self->{source}->{pointer}, $self->{title};
}

sub TO_JSON {
    my $self = shift;
    my $json = {};
    for (qw/code detail id links meta source status title/) {
        $json->{$_} = $self->$_ if $self->$_;
    }
    return $json;
}

1;

__END__

=encoding utf-8

=head1 NAME

JSON::API::Error - JSON API-style error objects

=head1 SYNOPSIS

  use JSON::API::Error;
  use Mojo::JSON qw/encode_json/;

  # A JSON API error representing bad submission data
  my $err = JSON::API::Error->new({
      source => {pointer => '/forename'},
      status => '400',
      title  => 'Field required',
  });

  # Field required
  say $err->title;
  # /forename: Field required
  say "$err";

  # {
  #   "source": {
  #     "pointer": "/forename"
  #   },
  #   "status": "400",
  #   "title": "Field required"
  # }
  say encode_json $err;
  say encode_json $err->TO_JSON;

  # A JSON API error representing a missing resource
  my $err = JSON::API::Error->new({
      status => '404',
      title  => 'Not Found',
  });



( run in 1.022 second using v1.01-cache-2.11-cpan-39bf76dae61 )