From 3dc7d5cba044e16776291f520fd68ac190bcbfb6 Mon Sep 17 00:00:00 2001 From: Matias Linares Date: Tue, 13 Feb 2018 20:53:30 -0300 Subject: Add simple error handling --- lib/Matrix/Client/Exception.pm6 | 10 ++++++++++ lib/Matrix/Client/Requester.pm6 | 28 +++++++++++++++++++--------- 2 files changed, 29 insertions(+), 9 deletions(-) create mode 100644 lib/Matrix/Client/Exception.pm6 (limited to 'lib/Matrix') diff --git a/lib/Matrix/Client/Exception.pm6 b/lib/Matrix/Client/Exception.pm6 new file mode 100644 index 0000000..924eece --- /dev/null +++ b/lib/Matrix/Client/Exception.pm6 @@ -0,0 +1,10 @@ +package X::Matrix { + class Response is Exception { + has $.code; + has $.error; + + method message { + "$!code: $!error" + } + } +} diff --git a/lib/Matrix/Client/Requester.pm6 b/lib/Matrix/Client/Requester.pm6 index b13272b..0bb7e3a 100644 --- a/lib/Matrix/Client/Requester.pm6 +++ b/lib/Matrix/Client/Requester.pm6 @@ -2,6 +2,7 @@ use HTTP::UserAgent; use HTTP::Request::Common; use URI::Encode; use JSON::Tiny; +use Matrix::Client::Exception; unit role Matrix::Client::Requester; @@ -12,14 +13,22 @@ has $!url-prefix = ""; has $!access-token = ""; has $!sync-since = ""; +method !handle-error($response) { + unless $response.is-success { + my $data = from-json($response.content); + X::Matrix::Response.new(:code($data), :error($data)).throw; + } + $response +} + method get(Str $path, :$media = False, *%data) { my $q = "$path?access_token=$!access-token"; for %data.kv -> $k,$v { - $q ~= "&$k=$v" unless $v eq ""; + $q ~= "&$k=$v" if $v.so; } my $uri = uri_encode($.base-url(:$media) ~ $q); - $!ua.get($uri) + return self!handle-error($!ua.get($uri)); } method base-url(Bool :$media? = False --> Str) { @@ -34,23 +43,24 @@ multi method post(Str $path, Str $json, :$media = False) { my $req = HTTP::Request.new(POST => $.base-url(:$media) ~ $path ~ "?access_token=$!access-token", Content-Type => 'application/json'); $req.add-content($json); - $!ua.request($req) -} -method post-bin(Str $path, Buf $buf, :$content-type) { - my $req = POST($.base-url(:media) ~ $path ~ "?access_token=$!access-token", content => $buf, Content-Type => $content-type); - $!ua.request($req) + return self!handle-error($!ua.request($req)); } multi method post(Str $path, :$media = False, *%params) { self.post($path, :$media, to-json(%params)) } -multi method put(Str $path,Str $json) { +method post-bin(Str $path, Buf $buf, :$content-type) { + my $req = POST($.base-url(:media) ~ $path ~ "?access_token=$!access-token", content => $buf, Content-Type => $content-type); + return self!handle-error($!ua.request($req)); +} + +multi method put(Str $path, Str $json) { my $req = HTTP::Request.new(PUT => $.base-url() ~ $path ~ "?access_token=$!access-token", Content-Type => 'application/json'); $req.add-content($json); - $!ua.request($req) + return self!handle-error($!ua.request($req)) } multi method put(Str $path, *%params) { -- cgit v1.2.3-54-g00ecf