Skip to content

Commit

Permalink
Merge pull request #276 from andrzejd-pl/dev
Browse files Browse the repository at this point in the history
Add new Exception for JSON errors
  • Loading branch information
nategood authored Jan 25, 2020
2 parents c1cd4d4 + 9ae25f3 commit cd9b569
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
7 changes: 7 additions & 0 deletions src/Httpful/Exception/JsonParseException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Httpful\Exception;

class JsonParseException extends \Exception
{
}
4 changes: 3 additions & 1 deletion src/Httpful/Handlers/JsonHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

namespace Httpful\Handlers;

use Httpful\Exception\JsonParseException;

class JsonHandler extends MimeHandlerAdapter
{
private $decode_as_array = false;
Expand All @@ -27,7 +29,7 @@ public function parse($body)
return null;
$parsed = json_decode($body, $this->decode_as_array);
if (is_null($parsed) && 'null' !== strtolower($body))
throw new \Exception("Unable to parse response as JSON");
throw new JsonParseException('Unable to parse response as JSON: ' . json_last_error_msg());
return $parsed;
}

Expand Down
4 changes: 2 additions & 2 deletions tests/Httpful/HttpfulTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -570,8 +570,8 @@ public function testParseJSON()

try {
$result = $handler->parse('invalid{json');
} catch(\Exception $e) {
$this->assertEquals('Unable to parse response as JSON', $e->getMessage());
} catch (\Httpful\Exception\JsonParseException $e) {
$this->assertEquals('Unable to parse response as JSON: ' . json_last_error_msg(), $e->getMessage());
return;
}
$this->fail('Expected an exception to be thrown due to invalid json');
Expand Down

0 comments on commit cd9b569

Please sign in to comment.